For the basics of DataGrid please refer this post: https://jitendrazaa.com/blog/?p=188
In this example, i will explain the basics of DataGrid control like Theming, Databinding etc.
We will start our example with creating the SQL Express database of Employee which will contain the following fields : Id, FName, LName, Email.
Now create a stored procedure to insert the data into Table.
CREATE PROCEDURE dbo.AddEmployee @FName varchar(50), @LName varchar(50), @Email varchar(50) AS INSERT INTO Employee (FName,LName,Email) values (@FName,@LName,@Email)
In ASPX page, write the code to input the Employee information.
First Name : <asp:TextBox ID="txtFName" runat="server"/><br /> Last Name :<asp:TextBox ID="txtLName" runat="server"/><br /> Email :<asp:TextBox ID="txtEmail"; runat="server"/><br /> <asp:Button ID="btnSubmit" Text="Add Record" runat="server" OnClick="btnSubmit_Click"/>
Go to the property of Employee.mdf and select connection string as shown in below image.
On the click event of the button write below function:
string conString = @"Data Source=.SQLEXPRESS;AttachDbFilename=""|DataDirectory|Employee.mdf"";Integrated Security=True;User Instance=True"; protected void btnSubmit_Click(object sender, EventArgs e) { SqlConnection con = null; SqlCommand cmd = null; try { con = new SqlConnection(conString); con.Open(); cmd = new SqlCommand("AddEmployee", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FName", txtFName.Text); cmd.Parameters.AddWithValue("@LName", txtLName.Text); cmd.Parameters.AddWithValue("@Email", txtEmail.Text); cmd.ExecuteNonQuery(); showConfirmationMessage(); } catch (CustomException ex) { ex.logException(); }finally{ con.Close(); } } private void showConfirmationMessage() { ClientScriptManager csMngr = Page.ClientScript; csMngr.RegisterStartupScript(Page.GetType(), "Success", "alert('Record Added succesfully');", true); }
ASPX Code for data grid
<asp:DataGrid ID="grdEmp" runat="server"> <HeaderStyle CssClass="Header" /> <AlternatingItemStyle CssClass="AlternateItemStyle" /> </asp:DataGrid>
Write below code to bind the data into DataGrid.
private void bindData() { SqlConnection con = null; SqlDataAdapter adp = null; try { con = new SqlConnection(conString); con.Open(); adp = new SqlDataAdapter("Select * from Employee",con); DataSet ds = new DataSet(); adp.Fill(ds); grdEmp.DataSource = ds; grdEmp.DataBind(); } catch (CustomException ex) { ex.logException(); }finally{ con.Close(); } }
Leave a Reply