DataGrid Example – Part 1

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();
}
}

Final output:

Download Code

Posted

in

by


Related Posts

Comments

One response to “DataGrid Example – Part 1”

  1. […] For Part 1, visit This URL https://jitendrazaa.com/blog/?p=191 […]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading