Select, Update, And Delete Data In A ASP.NET GridView Control

In this article, I will show you how to use an ASP.NET 2.0 GridView control to Select, update, and delete data in a SQL database.

We will use SQL Client data provider to provide database connectivity.

Before you can use any classes related to SQL Client data adapter, we need to import the SqlClient namespace in your application by using the following using statement.

  1. using System.Data.SqlClient;  

 

Next, we need to define the database connection string.

The below is my connection string which is stored in web.config file. You can change this connection string according to your SQL server database setting. I am storing my database file in App_Data folder. If you want use my database file then attach that file.

  1. <appSettings>  
  2.     <add key="connect" value="Initial Catalog=Data; Data Source=DHARMENDRA\SQLSERVER2005; uid=sa; pwd=wintellect" />  
  3. </appSettings>  

The following code snippet shows how to connect to a database and create other database access related objects.

  1. SqlDataAdapter da;  
  2. SqlConnection con;  
  3. DataSet ds = new DataSet();  
  4. SqlCommand cmd = new SqlCommand();  

This function is use to fetch data from the StudentRecord table, fills data in a DataTable object and find it to a GridView control using the DataSource property. In the end, the code calls the GridView.DataBind method to apply the binding.

  1. public void BindData() {  
  2.     con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);  
  3.     cmd.CommandText = "Select * from StudentRecord";  
  4.     cmd.Connection = con;  
  5.     da = new SqlDataAdapter(cmd);  
  6.     da.Fill(ds);  
  7.     con.Open();  
  8.     cmd.ExecuteNonQuery();  
  9.     GridView1.DataSource = ds;  
  10.     GridView1.DataBind();  
  11.     con.Close();  
  12. }  

Now on the page load method, we call the FillStudentRecordGrid method.

  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     if (!Page.IsPostBack) {  
  3.         BindData();  
  4.     }  
  5. }  

Now, next step is to set the GridView control settings.

The ASP.NET code for the DataView control. In this code below code, you see database table columns binding with the bound fields and formatting is provided using the template fields. If you are using my database, just copy and paste the code or use the attached application. If you are using your database, you need to replace column binding with your database table columns.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextGridview.aspx.cs" Inherits="sapnamalik_TextGridview" %>  
  2.     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head runat="server">  
  6.         <title>Untitled Page</title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="form1" runat="server">  
  11.             <div>  
  12.                 <asp:GridView ID="GridView1" runat="server" PageSize="3" AutoGenerateColumns="false" AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting">  
  13.                     <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />  
  14.                     <RowStyle BackColor="White" ForeColor="#330099" />  
  15.                     <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />  
  16.                     <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />  
  17.                     <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />  
  18.                     <Columns>  
  19.                         <asp:TemplateField HeaderText="StId">  
  20.                             <ItemTemplate>  
  21.                                 <asp:Label ID="lblstid" runat="server" Text='<%#Eval ("stId")%>'></asp:Label>  
  22.                             </ItemTemplate>  
  23.                         </asp:TemplateField>  
  24.                         <asp:TemplateField HeaderText="Name">  
  25.                             <ItemTemplate>  
  26.                                 <asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name")%>'> </asp:TextBox>  
  27.                             </ItemTemplate>  
  28.                         </asp:TemplateField>  
  29.                         <asp:TemplateField HeaderText="ClassName">  
  30.                             <ItemTemplate>  
  31.                                 <asp:TextBox ID="txtClassName" runat="server" Text='<%#Eval ("Classname") %>'></asp:TextBox>  
  32.                             </ItemTemplate>  
  33.                         </asp:TemplateField>  
  34.                         <asp:TemplateField HeaderText="RollNo">  
  35.                             <ItemTemplate>  
  36.                                 <asp:TextBox ID="txtRollNo" runat="server" Text='<%#Eval ("rollno")%>'> </asp:TextBox>  
  37.                             </ItemTemplate>  
  38.                         </asp:TemplateField>  
  39.                         <asp:TemplateField HeaderText="EmailId">  
  40.                             <ItemTemplate>  
  41.                                 <asp:TextBox ID="txtEmailId" runat="server" Text='<%#Eval ("emailId")%>'> </asp:TextBox>  
  42.                             </ItemTemplate>  
  43.                         </asp:TemplateField>  
  44.                         <asp:TemplateField HeaderText="Edit" ShowHeader="false">  
  45.                             <EditItemTemplate>  
  46.                                 <asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update" CommandName="Update"></asp:LinkButton>  
  47.                                 <asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel" CommandName="Cancel"></asp:LinkButton>  
  48.                             </EditItemTemplate <ItemTemplate>  
  49.                             <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit" Text="Edit"></asp:LinkButton>  
  50.                             </ItemTemplate>  
  51.                         </asp:TemplateField>  
  52.                         <asp:CommandField HeaderText="Delete" ShowDeleteButton="true" ShowHeader="true" />  
  53.                         <asp:CommandField HeaderText="Select" ShowSelectButton="true" ShowHeader="true" /> </Columns>  
  54.                 </asp:GridView <table>  
  55.                 <tr>  
  56.                     <td>  
  57.                         <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>  
  58.                         <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  
  59.                     </td>  
  60.                     <td>  
  61.                         <asp:Label ID="lblClassName" runat="server" Text="ClassName"></asp:Label>  
  62.                         <asp:TextBox ID="txtClassName" runat="server"></asp:TextBox>  
  63.                     </td>  
  64.                     <td>  
  65.                         <asp:Label ID="lblRollNo" runat="server" Text="RollNo"></asp:Label>  
  66.                         <asp:TextBox ID="txtRollNo" runat="server"></asp:TextBox>  
  67.                     </td>  
  68.                     <td>  
  69.                         <asp:Label ID="lblEmailId" runat="server" Text="EmailId"></asp:Label>  
  70.                         <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>  
  71.                     </td>  
  72.                     <td>  
  73.                         <asp:Label ID="lblTotalRecord" runat="server" Text="TotalRecord"></asp:Label>  
  74.                         <asp:TextBox ID="txtTotalRecord" runat="server"></asp:TextBox>  
  75.                     </td>  
  76.                 </tr>  
  77.                 <tr>  
  78.                     <td>  
  79.                         <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click1" />  
  80.                         <asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click1" /> </td>  
  81.                 </tr>  
  82.                 </table>  
  83.             </div>  
  84.         </form>  
  85.     </body>  
  86.   
  87.     </html>  

Now build and run the application. The results looks like following.

Figure 1.

1.gif

Select command is used to select a particular row on select LinkButton click

  1. <asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />  

 

Result looks like this on the select link.

Figure 2.

2.gif

This event is used for paging. As you can see from the code below, we simply set a new page index and rebind the data.

  1. protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {  
  2.     GridView1.PageIndex = e.NewPageIndex;  
  3.     BindData();  
  4. }  

This event shows how to delete a row on delete LinkButton click.

  1. protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) {  
  2.     con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);  
  3.     cmd.Connection = con;  
  4.     Label lbldeleteID = (Label) GridView1.Rows[e.RowIndex].FindControl("lblstId");  
  5.     cmd.CommandText = "Delete from StudentRecord where StId='" + lbldeleteID.Text + "'";  
  6.     con.Open();  
  7.     cmd.ExecuteNonQuery();  
  8.     con.Close();  
  9.     BindData();  
  10. }  

This event is used to show a row in editable mode.

  1. protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {  
  2.     GridView1.EditIndex = e.NewEditIndex;  
  3.     BindData();  
  4. }  

This event will update information in database.

  1. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {  
  2.     con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);  
  3.     Label lblstid = (Label) GridView1.Rows[e.RowIndex].FindControl("lblstId");  
  4.     TextBox txtname = (TextBox) GridView1.Rows[e.RowIndex].FindControl("txtName");  
  5.     TextBox txtclassname = (TextBox) GridView1.Rows[e.RowIndex].FindControl("txtClassName");  
  6.     TextBox txtrollno = (TextBox) GridView1.Rows[e.RowIndex].FindControl("txtRollNo");  
  7.     TextBox txtemailid = (TextBox) GridView1.Rows[e.RowIndex].FindControl("txtEmailId");  
  8.     cmd.Connection = con;  
  9.     cmd.CommandText = "Update StudentRecord set Name='" + txtname.Text + "',ClassName='" + txtclassname.Text + "',RollNo='" + txtrollno.Text + "',EmailId='" + txtemailid.Text + "' where StId='" + lblstid.Text + "'";  
  10.     cmd.Connection.Open();  
  11.     cmd.ExecuteNonQuery();  
  12.     GridView1.EditIndex = -1;  
  13.     BindData();  
  14.     con.Close();  
  15. }  

Result will look like this

Figure 3.


3.gif

This event is used to cancel editable model.

  1. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {  
  2.     GridView1.EditIndex = -1;  
  3.     BindData();  
  4. }