GridView Insert, Update, and Delete in ASP.Net Using C#

GridViews are useful for displaying data from a database. A GridView allows us to display items in the two-dimensional grid. It is mostly used to build video, image, audio galleries and so on and it provides us more flexibility for displaying and working with data from the database compared to other controls. The GridView Control enables us to connect to a Data Source and display the data in tabular format. The GridView control displays the values of a data source in a table. The GridView control supports the following features:

  • Multiple fields for the hyperlink columns.
  • Multiple key fields.
  • Built-in sort capabilities.
  • Built-in paging capabilities.
  • Customizable appearance through themes and styles.

This article shows how to use a GridView control in ASP.NET using C# code. So in this we will perform the following operations on GridView.

  • Edit Data in GridView.
  • Update Data in GridView.
  • Delete rows in GridView.
  • Bind data in GridView column.

Step 1

Start Visual Studio.


Figure 1: Start Visual Studio 

Step 2

Now for creating a website, click on File, go to New and click on Website.


Figure 2: Create Website

Step 3

Now add the Web Form by right-clicking on the website and then provide the name for the Web Form just added.


Figure 3: Add the Web Form 

Step 4

After adding the Web Form we will take the GridView control and design the Web Form as in the following:


Figure 4: Design Form 

We also need to create a table and make the ID column Primary Key for improving the performance of the GridView and restricting the duplicacy in the data. For this, we will create a table like the following:


Figure 5: Create Table

We will insert the data in the table as in the following:


Figure 6: Insert Data 

Step 5

After creating the table, we need to write the following code in the Default.aspx page.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <style type="text/css">  
  9.         .auto-style1 
            {  
  10.             text-align: center;  
  11.         }  
  12.     </style>  
  13. </head>  
  14. <body>  
  15.     <form id="form1" runat="server">  
  16.         <center>  
  17.         <div>  
  18.             <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="None" Height="280px" Width="472px">  
  19.                 <AlternatingRowStyle BackColor="PaleGoldenrod" />  
  20.                 <Columns>  
  21.                     <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />  
  22.                     <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />  
  23.                     <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />  
  24.                 </Columns>  
  25.                 <FooterStyle BackColor="Tan" />  
  26.                 <HeaderStyle BackColor="Tan" Font-Bold="True" />  
  27.                 <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />  
  28.                 <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />  
  29.                 <SortedAscendingCellStyle BackColor="#FAFAE7" />  
  30.                 <SortedAscendingHeaderStyle BackColor="#DAC09E" />  
  31.                 <SortedDescendingCellStyle BackColor="#E1DB9C" />  
  32.                 <SortedDescendingHeaderStyle BackColor="#C2A47B" />  
  33.             </asp:GridView>  
  34.             <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:yatendraConnectionString %>" SelectCommand="SELECT * FROM [grid1]" UpdateCommand="update [grid1] set [name]=@name,city=@city where [ID] = @ID " DeleteCommand="DELETE FROM [grid1] WHERE [ID] = @ID ">                
  35.             </asp:SqlDataSource>           
  36.             <br />  
  37.             <br />  
  38.             <div class="auto-style1">  
  39.                <label>  
  40.                    Name  
  41.                </label>   
  42.                 <asp:TextBox ID="TextBox1" runat="server" Width="198px"></asp:TextBox>  
  43.                 <br />  
  44.                 <br />  
  45.               <label>  
  46.                    City  
  47.                </label>   
  48.                 <asp:TextBox ID="TextBox2" runat="server" Width="198px" style="margin-left: 9px"></asp:TextBox>  
  49.                 <br />  
  50.                 <br />  
  51.                 <asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Button1_Click" BorderColor="#993366" ForeColor="#FF9999" />  
  52.                 <asp:Button ID="Button2" runat="server" Text="Reset" OnClick="Button2_Click" ForeColor="#CC3399" />  
  53.                 </center>  
  54.              </div>  
  55.         </div>  
  56.     </form>  
  57. </body>  
  58. </html>  
Step 6

In the Default.aspx page we will add the following two namespaces.

using System.Data;
using System.Data.SqlClient;


After writing the code on default.aspx page we will write the following code on Button1_Click.

  1. protected void Button1_Click(object sender, EventArgs e)  
  2.     {  
  3.         SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP34;Initial Catalog=yatendra;Persist Security Info=True;User ID=sa;Pa        ssword=Password$2");  
  4.         con.Open();  
  5.         SqlCommand cmd = con.CreateCommand();  
  6.         cmd.CommandType = CommandType.Text;  
  7.         cmd.CommandText = "insert into grid1 values ('" + TextBox1.Text + "','" + TextBox2.Text + "')";  
  8.         cmd.ExecuteNonQuery();  
  9.         Response.Write("Data Inserted Sucessfully");  
  10.         con.Close();  
  11.         Response.Redirect("default.aspx");  
  12.     }  

Step 7

Now we will execute the website by using the F5 key. After execution, the following window appears on the screen.


Figure 7: Execute Form

Step 8

Now we need to ensure that GridView edit, update and delete operations are working. When we provide the values in the Name and City textboxes and click on the insert button, we will get the following window:


Figure 8: Insert Operation 


Figure 9: Data Inserted

So the data is inserted successfully into the GridView as well as in the database.

Step 9

Now we need to perform another operation of deletion. For this, clicking on the delete button will delete the data successfully as in the following screenshot.

 

Figure 10: Delete Operation 
 
Figure 11: Data Deleted

Step 10

Now we will perform the edit operation in the GridView.


Figure 12:  Edit Operation


Figure 13: Data Updated

So the edit operation is also working perfectly.

Summary

In this article, I explained how to perform the insert, update and delete operations in GridView. Now, you can easily perform these operations in your projects.

I hope this article will be helpful for beginners if they want to perform insert, update and delete operations in their project to make it more effective.