CRUD Operations in GridView Using ASP.Net

Previously I wrote this same article but with 3 tiers. That was a long process, but here we will not use 3 tiers and instead put alll the code in a single .cs file.

Initial chamber

Step 1

Open your Visual Studio 2010 and create an empty website. Name it gridview_demo.

Step 2

In Solution Explorer you will see your empty website, add a web form and a SQL Server database as in the following.

For Web Form:

gridview_demo (your empty website) then right-click then select Add New Item -> Web Form. Name it gridview_demo.aspx.

For SQL Server Database

gridview_demo (your empty website) then right-click then select Add New Item -> SQL Server Database. Add the database inside the App_Data_folder.

DATABASE CHAMBER

Step 3

In Server Explorer, click on your database (Database.mdf) then select Tables -> Add New Table. Make the table like this.

Go to your database (Database.mdf) and create a table tbl_Data. Go to the database.mdf, then Table and Add New table. Design your table like the following:

Table tbl_data (don't forget to make ID as IS Identity -- True)


table design

I included a Stored Procedure for the update operation, so if someone wants to know how to make it using a Stored Procedure then they can learn from here.

Sp_updatedata -  Database.mdf, the go to Stored Procedure and Add New Stored Procedure.

Add New Store Procedure

Design chamber

Step 4

Now open your gridview_demo.aspx file, where we create our design for binding and performing create, edit, delete and update operations.

Gridview_demo.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <style type="text/css">  
  9.         .style1  
  10.         {  
  11.             text-decoration: underline;  
  12.             color: #0000FF;  
  13.         }  
  14.     </style>  
  15. </head>  
  16. <body>  
  17.     <form id="form1" runat="server">  
  18.     <table style="width:100%;">  
  19.         <tr>  
  20.             <td class="style1">  
  21.                 <strong>Edit Update Delete Operation in Gridview</strong></td>  
  22.             <td>  
  23.                  </td>  
  24.             <td>  
  25.                  </td>  
  26.         </tr>  
  27.         <tr>  
  28.             <td>  
  29.                 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"   
  30.                     BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"   
  31.                     CellPadding="3" DataKeyNames="id" AutoGenerateDeleteButton="True"   
  32.                     AutoGenerateEditButton="True" onrowcancelingedit="GridView1_RowCancelingEdit"   
  33.                     onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"   
  34.                     onrowupdating="GridView1_RowUpdating" CellSpacing="2">  
  35.                     <Columns>  
  36.                         <asp:TemplateField HeaderText="Name">  
  37.                             <EditItemTemplate>  
  38.                                 <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>  
  39.                             </EditItemTemplate>  
  40.                             <ItemTemplate>  
  41.                                 <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>  
  42.                             </ItemTemplate>  
  43.                         </asp:TemplateField>  
  44.                         <asp:TemplateField HeaderText="City">  
  45.                             <EditItemTemplate>  
  46.                                 <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>  
  47.                             </EditItemTemplate>  
  48.                             <ItemTemplate>  
  49.                                 <asp:Label ID="Label2" runat="server" Text='<%# Bind("city") %>'></asp:Label>  
  50.                             </ItemTemplate>  
  51.                         </asp:TemplateField>  
  52.                     </Columns>  
  53.                     <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
  54.                     <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />  
  55.                     <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
  56.                     <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
  57.                     <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
  58.                     <SortedAscendingCellStyle BackColor="#FFF1D4" />  
  59.                     <SortedAscendingHeaderStyle BackColor="#B95C30" />  
  60.                     <SortedDescendingCellStyle BackColor="#F1E5CE" />  
  61.                     <SortedDescendingHeaderStyle BackColor="#93451F" />  
  62.                 </asp:GridView>  
  63.             </td>  
  64.             <td>  
  65.                  </td>  
  66.             <td>  
  67.                  </td>  
  68.         </tr>  
  69.         <tr>  
  70.             <td>  
  71.                  </td>  
  72.             <td>  
  73.                  </td>  
  74.             <td>  
  75.                  </td>  
  76.         </tr>  
  77.     </table>  
  78.     <div>  
  79.       
  80.     </div>  
  81.     </form>  
  82. </body>  
  83. </html>  
Your design will look like the following:

Design

You need to look around this Property in GridView:
  1. DataKeysName: id
  2. Auto Generate Delete Button: True
  3. Auto Generate Edit Button : True

In events (double-click each event shown below to go to the code):

  1. Row Canceling Edit
  2. Row Deleting
  3. Row Editing
  4. Row Updating

    Properties

Code chamber

Step 5

Open your gridview_demo.aspx.cs and write some code so that our application works.

Gridview_demo.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9.   
  10. public partial class Default2 : System.Web.UI.Page  
  11. {  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.         if (!Page.IsPostBack)  
  15.         {  
  16.             refreshdata();  
  17.         }  
  18.     }  
  19.   
  20.     public void refreshdata()  
  21.     {  
  22.         SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  23.         SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  24.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  25.         DataTable dt = new DataTable();  
  26.         sda.Fill(dt);  
  27.         GridView1.DataSource = dt;  
  28.         GridView1.DataBind();  
  29.       
  30.       
  31.     }  
  32.   
  33.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  34.     {  
  35.         SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  36.         int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());  
  37.         con.Open();  
  38.         SqlCommand cmd = new SqlCommand("delete from tbl_data where id =@id", con);  
  39.         cmd.Parameters.AddWithValue("id", id);  
  40.         int i = cmd.ExecuteNonQuery();  
  41.         con.Close();  
  42.         refreshdata();  
  43.     }  
  44.   
  45.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  46.     {  
  47.         GridView1.EditIndex = e.NewEditIndex;  
  48.         refreshdata();  
  49.     }  
  50.   
  51.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  52.     {  
  53.         GridView1.EditIndex = -1;  
  54.         refreshdata();  
  55.     }  
  56.      
  57.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  58.     {  
  59.         SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  60.           
  61.         TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox1"as TextBox;  
  62.         TextBox txtcity = GridView1.Rows[e.RowIndex].FindControl("TextBox2"as TextBox;  
  63.         int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());  
  64.         con.Open();  
  65.         SqlCommand cmd = new SqlCommand("sp_updatedata", con);  
  66.         cmd.CommandType = CommandType.StoredProcedure;  
  67.      
  68.         cmd.Parameters.AddWithValue("name", txtname.Text);  
  69.         cmd.Parameters.AddWithValue("city", txtcity.Text);  
  70.         cmd.Parameters.AddWithValue("id", id);  
  71.       
  72.         int i = cmd.ExecuteNonQuery();  
  73.         con.Close();  
  74.         GridView1.EditIndex = -1;  
  75.         refreshdata();  
  76.         
  77.          
  78.     }  
  79.       
  80. }  
Output chamber

Binded Gridview


Update data

I hope you like it. All controls are working, you can check it out. Thank you for reading.


Similar Articles