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. <!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. <head runat="server">
  5. <title></title>
  6. <style type="text/css">
  7. .style1
  8. {
  9. text-decoration: underline;
  10. color: #0000FF;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <form id="form1" runat="server">
  16. <table style="width:100%;">
  17. <tr>
  18. <td class="style1">
  19. <strong>Edit Update Delete Operation in Gridview</strong></td>
  20. <td>
  21. </td>
  22. <td>
  23. </td>
  24. </tr>
  25. <tr>
  26. <td>
  27. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
  28. BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
  29. CellPadding="3" DataKeyNames="id" AutoGenerateDeleteButton="True"
  30. AutoGenerateEditButton="True" onrowcancelingedit="GridView1_RowCancelingEdit"
  31. onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
  32. onrowupdating="GridView1_RowUpdating" CellSpacing="2">
  33. <Columns>
  34. <asp:TemplateField HeaderText="Name">
  35. <EditItemTemplate>
  36. <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
  37. </EditItemTemplate>
  38. <ItemTemplate>
  39. <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
  40. </ItemTemplate>
  41. </asp:TemplateField>
  42. <asp:TemplateField HeaderText="City">
  43. <EditItemTemplate>
  44. <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
  45. </EditItemTemplate>
  46. <ItemTemplate>
  47. <asp:Label ID="Label2" runat="server" Text='<%# Bind("city") %>'></asp:Label>
  48. </ItemTemplate>
  49. </asp:TemplateField>
  50. </Columns>
  51. <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
  52. <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
  53. <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
  54. <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
  55. <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
  56. <SortedAscendingCellStyle BackColor="#FFF1D4" />
  57. <SortedAscendingHeaderStyle BackColor="#B95C30" />
  58. <SortedDescendingCellStyle BackColor="#F1E5CE" />
  59. <SortedDescendingHeaderStyle BackColor="#93451F" />
  60. </asp:GridView>
  61. </td>
  62. <td>
  63. </td>
  64. <td>
  65. </td>
  66. </tr>
  67. <tr>
  68. <td>
  69. </td>
  70. <td>
  71. </td>
  72. <td>
  73. </td>
  74. </tr>
  75. </table>
  76. <div>
  77. </div>
  78. </form>
  79. </body>
  80. </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. public partial class Default2 : System.Web.UI.Page
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {
  13. if (!Page.IsPostBack)
  14. {
  15. refreshdata();
  16. }
  17. }
  18. public void refreshdata()
  19. {
  20. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
  21. SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
  22. SqlDataAdapter sda = new SqlDataAdapter(cmd);
  23. DataTable dt = new DataTable();
  24. sda.Fill(dt);
  25. GridView1.DataSource = dt;
  26. GridView1.DataBind();
  27. }
  28. protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  29. {
  30. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
  31. int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
  32. con.Open();
  33. SqlCommand cmd = new SqlCommand("delete from tbl_data where id =@id", con);
  34. cmd.Parameters.AddWithValue("id", id);
  35. int i = cmd.ExecuteNonQuery();
  36. con.Close();
  37. refreshdata();
  38. }
  39. protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
  40. {
  41. GridView1.EditIndex = e.NewEditIndex;
  42. refreshdata();
  43. }
  44. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  45. {
  46. GridView1.EditIndex = -1;
  47. refreshdata();
  48. }
  49. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
  50. {
  51. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
  52. TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;
  53. TextBox txtcity = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
  54. int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
  55. con.Open();
  56. SqlCommand cmd = new SqlCommand("sp_updatedata", con);
  57. cmd.CommandType = CommandType.StoredProcedure;
  58. cmd.Parameters.AddWithValue("name", txtname.Text);
  59. cmd.Parameters.AddWithValue("city", txtcity.Text);
  60. cmd.Parameters.AddWithValue("id", id);
  61. int i = cmd.ExecuteNonQuery();
  62. con.Close();
  63. GridView1.EditIndex = -1;
  64. refreshdata();
  65. }
  66. }
Output chamber

Binded Gridview


Update data

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