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)
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.
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
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <style type="text/css">
- .style1
- {
- text-decoration: underline;
- color: #0000FF;
- }
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <table style="width:100%;">
- <tr>
- <td class="style1">
- <strong>Edit Update Delete Operation in Gridview</strong></td>
- <td>
- </td>
- <td>
- </td>
- </tr>
- <tr>
- <td>
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
- BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
- CellPadding="3" DataKeyNames="id" AutoGenerateDeleteButton="True"
- AutoGenerateEditButton="True" onrowcancelingedit="GridView1_RowCancelingEdit"
- onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
- onrowupdating="GridView1_RowUpdating" CellSpacing="2">
- <Columns>
- <asp:TemplateField HeaderText="Name">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="City">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label2" runat="server" Text='<%# Bind("city") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
- <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
- <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
- <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
- <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
- <SortedAscendingCellStyle BackColor="#FFF1D4" />
- <SortedAscendingHeaderStyle BackColor="#B95C30" />
- <SortedDescendingCellStyle BackColor="#F1E5CE" />
- <SortedDescendingHeaderStyle BackColor="#93451F" />
- </asp:GridView>
- </td>
- <td>
- </td>
- <td>
- </td>
- </tr>
- <tr>
- <td>
- </td>
- <td>
- </td>
- <td>
- </td>
- </tr>
- </table>
- <div>
-
- </div>
- </form>
- </body>
- </html>
Your design will look like the following:
You need to look around this Property in GridView:
- DataKeysName: id
- Auto Generate Delete Button: True
- Auto Generate Edit Button : True
In events (double-click each event shown below to go to the code):
- Row Canceling Edit
- Row Deleting
- Row Editing
- Row Updating
Code chamber
Step 5
Open your gridview_demo.aspx.cs and write some code so that our application works.
Gridview_demo.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
-
- public partial class Default2 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- refreshdata();
- }
- }
-
- public void refreshdata()
- {
- SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
- SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
- SqlDataAdapter sda = new SqlDataAdapter(cmd);
- DataTable dt = new DataTable();
- sda.Fill(dt);
- GridView1.DataSource = dt;
- GridView1.DataBind();
-
-
- }
-
- protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
- {
- SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
- int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
- con.Open();
- SqlCommand cmd = new SqlCommand("delete from tbl_data where id =@id", con);
- cmd.Parameters.AddWithValue("id", id);
- int i = cmd.ExecuteNonQuery();
- con.Close();
- refreshdata();
- }
-
- protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
- {
- GridView1.EditIndex = e.NewEditIndex;
- refreshdata();
- }
-
- protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
- {
- GridView1.EditIndex = -1;
- refreshdata();
- }
-
- protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
- {
- SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
-
- TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;
- TextBox txtcity = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
- int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
- con.Open();
- SqlCommand cmd = new SqlCommand("sp_updatedata", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.AddWithValue("name", txtname.Text);
- cmd.Parameters.AddWithValue("city", txtcity.Text);
- cmd.Parameters.AddWithValue("id", id);
-
- int i = cmd.ExecuteNonQuery();
- con.Close();
- GridView1.EditIndex = -1;
- refreshdata();
-
-
- }
-
- }
Output chamber
I hope you like it. All controls are working, you can check it out. Thank you for reading.