Update and Delete in GridView

In this article, we will look at how to update or delete a record in a database table using a GridView control.

The GridView control is a tabular databound control but sometimes it is used like a spreadsheet control. It came with ASP.NET 2.0 and is an improved version of the DataGrid control. It displays a set of data items in an HTML table. We can use this to display data from a database and edit, sort and select the data.

Database Table Structure

We are using an "EMPLOYEE" table so the "EMPLOYEE" table design is:

Image 1.jpg

Design of GridView

We design a GridView with which we can perform update and delete operations. Here we can update Name, Emp_Code and Emp_Age fields depending on the Id field of the "EMPLOYEE" table.

  1. <asp:GridView ID="gvEmployee" runat="server"          
  2.             AutoGenerateColumns="False"  
  3.             DataKeyNames="Id"  
  4.             onrowcancelingedit="gvEmployee_RowCancelingEdit"  
  5.             onrowediting="gvEmployee_RowEditing"              
  6.             onrowdeleting="gvEmployee_RowDeleting"  
  7.             onrowupdating="gvEmployee_RowUpdating"  
  8.             GridLines="None"  
  9.             AllowPaging="true"  
  10.             CssClass="mGrid"  
  11.             PagerStyle-CssClass="pgr"  
  12.             AlternatingRowStyle-CssClass="alt"  
  13.             Width=40%>  
  14.             <Columns>  
  15.                 <asp:TemplateField HeaderText="S.No." ItemStyle-HorizontalAlign="Center">  
  16.                     <ItemTemplate>  
  17.                         <%#Container.DataItemIndex+1%>  
  18.                     </ItemTemplate>  
  19.                 </asp:TemplateField>  
  20.                 <asp:TemplateField HeaderText="Employee Name">  
  21.                     <ItemTemplate>     
  22.                         <%#Eval("Name")%>     
  23.                     </ItemTemplate>  
  24.                     <EditItemTemplate>  
  25.                         <asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>  
  26.                     </EditItemTemplate>  
  27.                 </asp:TemplateField>  
  28.              <asp:TemplateField HeaderText="Employee Code">  
  29.                 <ItemTemplate>  
  30.                     <%#Eval("Emp_Code")%>  
  31.                 </ItemTemplate>  
  32.                 <EditItemTemplate>  
  33.                     <asp:TextBox ID="txtempcode" runat="server" Text='<%#Eval("Emp_Code") %>'></asp:TextBox>  
  34.                 </EditItemTemplate>  
  35.             </asp:TemplateField>  
  36.             <asp:TemplateField HeaderText="Employee Age">  
  37.                 <ItemTemplate>  
  38.                     <%#Eval("Emp_Age")%>  
  39.                 </ItemTemplate>  
  40.                 <EditItemTemplate>  
  41.                     <asp:TextBox ID="txtempage" runat="server" Text='<%#Eval("Emp_Age") %>'></asp:TextBox>  
  42.                 </EditItemTemplate>  
  43.             </asp:TemplateField>  
  44.             <asp:CommandField ShowEditButton="true" ButtonType ="Image" EditImageUrl="Image/edit.png" UpdateImageUrl="Image/accept.png"  
  45.             CancelImageUrl="Image/cancel.png" HeaderText="Edit" />  
  46.             <asp:CommandField ShowDeleteButton="true" ButtonType="Image" DeleteImageUrl="Image/delete.png" HeaderText="Delete" />   
  47.     </Columns>  
  48. </asp:GridView>
The following bulleted list describes each field of the GridView used in the design of it:

  • AutoGenerateColumns: This property accepts only a Boolean value. The default value is true. When we set it to False, the BoundField objects are not created automatically; we will create the fields manually. When we set it to True then all table fields are retrieved by the SQL query or Stored Procedure and also bound the with GridView and we get all field columns in the GridView with their records as well as manual records.

  • DataKeyNames: This property associates a value with each row in the GridView. Here we can assign the name of a single database column or more than one column. When we assign more than one database column then they are specified separated by commas. It represents datakey values. By this we uniquely identifiy records in GridView rows. Here we are using the "Id" field of the EMPLOYEE table; that field does not display in the GridView but this field value is used to access the table by row and can perform updates/deletes depending on this field value because it is the EMPLOYEE table's primary key field. Mostly it is a primary key field or unique field.

  • <Columns>: It is a collection of columns that the GridView contains. By this we can control what GridView columns are displayed, which means we can change the order of the appearance of the columns.

  • <asp:TemplateField>: Is used to add ASP.Net controls in GridView rows. One TemplateField represents one column in the GridView. It customizes the appearance of the UI in the GridView. It is useful when we are using a GridView to edit a database record.

  • <ItemTemplate>: It specifies the contents that are displayed in a TemplateField object. It displays a layout for the TemplateField.

  • <EditItemTemplate>: It also specifies contents that are displayed in a TemplateField but in EditMode.

  • Eval: It is a method that is used to display data. In this method we pass a database field name as an argument and that database field is displayed by this. This method is used when we will edit a row record otherwise we can use the Bind method.

  • <asp:CommandField>: It is a special field that displays command buttons to perform selecting, editing, inserting and deleting. Here we define the image type button so it can display an icon of the operation instead of their name.

Create SQL Connection

We need a connection with a Microsoft SQL Server database so we can access data and perform an operation on it. We define a connection in the web.config file and give a name to the connection string.

  1. <connectionStrings>  
  2.     <add name="connStr" connectionString="Data Source= sandeepss-PC;database=Development;user=sa;password=knowdev"/>  
  3. </connectionStrings>

Now we access this connection string on the .cs page so we can open a connection with the relation database. We need to use two namespaces. The first one accesses the connection string and the other is for the SQL connection.

  1. using System.Configuration;  
  2. using System.Data.SqlClient; 

Now we define a method for opening a connection with the relation database and returns a SQL connection object depending on the connection string that is passed as a parameter of the SqlConnection class constructor.

  1. private SqlConnection GetConnection()  
  2. {  
  3.     string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;  
  4.     SqlConnection con = new SqlConnection(connStr);  
  5.     con.Open();  
  6.     return con;  
  7. } 

Populate Employee Details

Create a Stored Procedure to retrieve all employee details from the "EMPLOYEE" table:

  1. CREATE PROCEDURE _sp_GetEmployeeDetail  
  2. AS  
  3. BEGIN  
  4.      SET NOCOUNT ON;  
  5.      SELECT Id,NAME, Emp_Code,Emp_Age FROM EMPLOYEE  
  6. END  
  7. GO 

We create a method to get all employee details and bind the retrieved data with the employee grid. So first we need to use a namespace, as in:

  1. using System.Data;
Now create a method for get employee details

  1. private void GetEmployeeDetail()  
  2. {  
  3.     SqlConnection con = GetConnection();  
  4.     DataTable dt = new DataTable();  
  5.     SqlCommand cmd = new SqlCommand("_sp_GetEmployeeDetail", con);  
  6.     cmd.CommandType = CommandType.StoredProcedure;  
  7.     if (con.State == ConnectionState.Closed)  
  8.     {  
  9.         con.Open();  
  10.         IDataReader dr = cmd.ExecuteReader();  
  11.         dt.Load(dr);  
  12.     }  
  13.     gvEmployee.DataSource = dt;  
  14.     gvEmployee.DataBind();  
  15.     con.Close();  
  16. } 

To populate the GridView we need to call this method on page load.

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

Image 2.jpg

Delete a Record

We can delete a record from the database table by clicking on the delete button that is in the Delete column of the GridView. We first of all create a Stored Procedure that gets the Id of an employee as a parameter from the GridView on whichever row the user clicked.

  1. CREATE PROCEDURE _sp_DeleteEmployee  
  2. (  
  3.      @Id int  
  4. )  
  5. AS  
  6. BEGIN  
  8. END  
  9. GO

Now we use the RowDeleting Event of GridView. In this event, first we get the datakey value that is the id of an employee of whichever row the user clicked and that id is passed as a parameter to the Stored Procedure. After that the GridView is rebound with new data.

  1. protected void gvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  2. {  
  3.     int id = Convert.ToInt32(gvEmployee.DataKeys[e.RowIndex].Value.ToString());  
  4.     SqlConnection con = GetConnection();  
  5.     SqlCommand cmd = new SqlCommand("_sp_DeleteEmployee", con);  
  6.     cmd.CommandType = CommandType.StoredProcedure;  
  7.     cmd.Parameters.AddWithValue("@Id", id);  
  8.     if (con.State == ConnectionState.Closed)  
  9.     {  
  10.         con.Open();  
  11.     }  
  12.     cmd.ExecuteNonQuery();  
  13.     GetEmployeeDetail();  
  14. } 

Update a Record

To update a record in the GridView we need to perform the following three operations:

  1. Row move in edit mode.

  2. Cancel edit operation and get original state without any update

  3. Update record and get updated state of GridView.

According to the above, in these three operations we use three events of the GridView for each operation. Point numbers 2 and 3 are performed after point 1 is performed.

1. Row move in edit mode

We have a GridView with records. We can't update a record until that record doesn't exist in the input type field (TextBox). So first we need to move to an updateable row record in the TextBox. To do that we need a RowEditing event of the GridView.

  1. protected void gvEmployee_RowEditing(object sender, GridViewEditEventArgs e)  
  2. {  
  3.     gvEmployee.EditIndex = e.NewEditIndex;  
  4.     GetEmployeeDetail();  
  5. }

2. Cancel the edit operation and get the original state without any update.

When the row is in edit mode and we don't want to update a record then we want to move to the original state of the GridView so we use the RowCancelingEdit event of the GridView.

  1. protected void gvEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  2. {  
  3.     gvEmployee.EditIndex = -1;  
  4.     GetEmployeeDetail();  
  5. }

Image 3.jpg

The EditIndex property of a GridView determines the index of a row in edit mode. EditIndex=-1 means that no row is in edit mode.

3. Update record and get updated state of the GridView.

When a GridView row is in edit mode then we can update the row's record in the relational database table. So we need to create a Stored Procedure on which we pass all parameters that are updateable along with the primary key value, in other words the row data's key value that is being updated.

  1. CREATE PROCEDURE _sp_UpdateEmployee  
  2. (  
  3.      @Id int,  
  4.      @Name nvarchar(30),  
  5.      @Emp_Code varchar(10),  
  6.      @Emp_Age int  
  7. )  
  8. AS  
  9. BEGIN  
  10.      UPDATE EMPLOYEE SET Name=@Name,  
  11.      Emp_Code=@Emp_Code,  
  12.      Emp_Age=@Emp_Age WHERE Id=@Id  
  13. END  
  14. GO 

We use the RowUpdating event of GridView to update the record in the database table. We get the Id value using the row index and another TextBox value is also retrieved. All updated values are passed to the Stored Procedure.

  1. protected void gvEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  2. {  
  3.     int id = Convert.ToInt32(gvEmployee.DataKeys[e.RowIndex].Value.ToString());  
  4.     string name = ((TextBox)gvEmployee.Rows[e.RowIndex].FindControl("txtempname")).Text;  
  5.     string emp_code = ((TextBox)gvEmployee.Rows[e.RowIndex].FindControl("txtempcode")).Text;  
  6.     int emp_age = Convert.ToInt32(((TextBox)gvEmployee.Rows[e.RowIndex].FindControl("txtempage")).Text);  
  7.     SqlConnection con = GetConnection();  
  8.     if (con.State == ConnectionState.Closed)  
  9.     {  
  10.         con.Open();  
  11.     }  
  12.     SqlCommand cmd = new SqlCommand("_sp_UpdateEmployee", con);  
  13.     cmd.CommandType = CommandType.StoredProcedure;  
  14.     cmd.Parameters.AddWithValue("@Id ", id);  
  15.     cmd.Parameters.AddWithValue("@Name ", name);  
  16.     cmd.Parameters.AddWithValue("@Emp_Code ", emp_code);  
  17.     cmd.Parameters.AddWithValue("@Emp_Age ", emp_age);  
  18.     cmd.ExecuteNonQuery();  
  19.     con.Close();  
  20.     gvEmployee.EditIndex = -1;// no row in edit mode  
  21.     GetEmployeeDetail();  
  22. }