In this article I will show you how to Bind GridView in 3 tier in ASP.Net using C# with Stored Procedure. We will also edit, delete and update the data in GridView.

Initial Chamber

Step 1: Open Visual Studio 2010 and create an Empty Website. Give it a suitable name [GridView_demo].

Step 2: In Solution Explorer you will get your empty website. Add a web form, SQL database and 3 class files. By going like this:

For Web Form

GridView_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as -> gridview_demo.aspx.

For SQL Server Database

GridView_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server Database. [Add Database inside the App_Data_folder].

For 3 Class Files

GridView_demo (Your Empty Website) -> Right Click -> Add New Item -> Class [Add 3 Class files - -> Add your class file in App_code Folder] - -> Give name as the following:

  1. Commonfunctions.cs
  2. BAL_user_operation.cs
  3. DAL_user_operation.cs

Database Chamber

Step 3: In Server Explorer, Click on your Database [Database.mdf] - -> Tables - -> Add New Table -:- Make table like the following:

Table - -> tbl_data [Don’t Forget to make ID as IS Identity -- True]

Add some Stored procedure for Update, Insert and Delete Data by going to Database [Database.mdf] - -> Stored Procedures - -> Right Click - -> Add New Stored Procedures.

  1. sp_getdata()



  2. sp_insert()



  3. sp_update()



  4. sp_delete()

These all are the Stored Procedures that we will use for updating, deleting and editing data in GridView.

Design Code

Step 5: Now it’s time for serious design in GridView. Let’s begin by opening gridview_demo.aspx page and try the following code:

  1. <body>
  2. <form id="form1" runat="server">
  3. <table style="width:100%;">
  4. <caption class="style3">
  5. <strong>Bind Grid View Using 3Tier</strong></caption>
  6. <tr>
  7. <td align="center">
  8. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
  9. BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
  10. CellPadding="2" DataKeyNames="id" ForeColor="Black" GridLines="None"
  11. AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
  12. onrowcancelingedit="GridView1_RowCancelingEdit"
  13. onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
  14. onrowupdating="GridView1_RowUpdating">
  15. <AlternatingRowStyle BackColor="PaleGoldenrod" />
  16. <Columns>
  17. <asp:TemplateField HeaderText="Name" SortExpression="name">
  18. <EditItemTemplate>
  19. <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
  20. </EditItemTemplate>
  21. <ItemTemplate>
  22. <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
  23. </ItemTemplate>
  24. </asp:TemplateField>
  25. <asp:TemplateField HeaderText="Email" SortExpression="email">
  26. <EditItemTemplate>
  27. <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
  28. </EditItemTemplate>
  29. <ItemTemplate>
  30. <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>
  31. </ItemTemplate>
  32. </asp:TemplateField>
  33. <asp:TemplateField HeaderText="City" SortExpression="city">
  34. <EditItemTemplate>
  35. <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
  36. </EditItemTemplate>
  37. <ItemTemplate>
  38. <asp:Label ID="Label2" runat="server" Text='<%# Bind("city") %>'></asp:Label>
  39. </ItemTemplate>
  40. </asp:TemplateField>
  41. </Columns>
  42. <FooterStyle BackColor="Tan" />
  43. <HeaderStyle BackColor="Tan" Font-Bold="True" />
  44. <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
  45. HorizontalAlign="Center" />
  46. <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
  47. <SortedAscendingCellStyle BackColor="#FAFAE7" />
  48. <SortedAscendingHeaderStyle BackColor="#DAC09E" />
  49. <SortedDescendingCellStyle BackColor="#E1DB9C" />
  50. <SortedDescendingHeaderStyle BackColor="#C2A47B" />
  51. </asp:GridView>
  52. </td>
  53. </tr>
  54. </table>
  55. </form>
  56. </body>

You can also manually create this design by dragging the GridView into .aspx page. Then click the arrow sign on GridView - -> GridView tasks will open - -> Edit Columns - -> A “Field” window will open (following image). Here you have to add three “BoundField” Button from - -> Available Fields. - -> Change the header text - -> Name, Email, City.

Unclick the Auto Generated Button at the bottom [Note: I forgot to unclick it.].

Get into Bound Field Properties - -> Data Fields - -> Change every Bound field’s Data field to - ->

Go to GridView [In design mode] - -> press F4 to open Property window of GridView and find - -> Data Keys Name - -> and write – id.

In Property Window find - -> Auto Generate Edit and Auto Generate Delete Button and make it - -> True.

This is your actual Design.

Code Chamber

  1. Open Commonfunction.cs file and add this code:
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. using System.Configuration;
    6. /// <summary>
    7. /// Summary description for Commonfunctions
    8. /// </summary>
    9. public class Commonfunctions
    10. {
    11. public Commonfunctions()
    12. {
    13. //
    14. // TODO: Add constructor logic here
    15. //
    16. }
    17. public static string getconstring()
    18. {
    19. return ConfigurationManager.ConnectionStrings["dbcon"].ToString();
    20. }
    21. }
    The preceding code is written for SQL Connection String that we have to call again and again by going to the database property. This is a lengthy process, that’s why we made this class and now we will just call its method - ->getconstring() that will make our process shorter and comfortable.

  2. Open DAL_user_operation.cs file and code it as in the following code.
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. using System.Data;
    6. using System.Data.SqlClient;
    7. /// <summary>
    8. /// Summary description for DAL_user_operation
    9. /// </summary>
    10. public class DAL_user_operation
    11. {
    12. public DAL_user_operation()
    13. {
    14. //
    15. // TODO: Add constructor logic here
    16. //
    17. }
    18. public bool user_insert(string name, string email,string city)
    19. {
    20. SqlConnection con = new SqlConnection(Commonfunctions.getconstring());
    21. SqlCommand cmd = new SqlCommand("sp_insert", con);
    22. cmd.CommandType = CommandType.StoredProcedure;
    23. cmd.Parameters.AddWithValue("name", name);
    24. cmd.Parameters.AddWithValue("email",email);
    25. cmd.Parameters.AddWithValue("city", city);
    26. con.Open();
    27. int i = cmd.ExecuteNonQuery();
    28. con.Close();
    29. if (i != 0)
    30. {
    31. return true;
    32. }
    33. else
    34. {
    35. return false;
    36. }
    37. }
    38. public void user_delete(int id)
    39. {
    40. SqlConnection con = new SqlConnection(Commonfunctions.getconstring());
    41. SqlCommand cmd = new SqlCommand("sp_delete", con);
    42. cmd.CommandType = CommandType.StoredProcedure;
    43. cmd.Parameters.AddWithValue("id", id);
    44. con.Open();
    45. int i = cmd.ExecuteNonQuery();
    46. con.Close();
    47. }
    48. public void user_update(string name, string email,string city, int id)
    49. {
    50. SqlConnection con = new SqlConnection(Commonfunctions.getconstring());
    51. SqlCommand cmd = new SqlCommand("sp_update", con);
    52. cmd.CommandType = CommandType.StoredProcedure;
    53. cmd.Parameters.AddWithValue("name", name);
    54. cmd.Parameters.AddWithValue("email",email);
    55. cmd.Parameters.AddWithValue("city", city);
    56. cmd.Parameters.AddWithValue("id", id);
    57. con.Open();
    58. int i = cmd.ExecuteNonQuery();
    59. con.Close();
    60. }
    61. public DataTable getdata()
    62. {
    63. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
    64. SqlCommand cmd = new SqlCommand("sp_getdata", con);
    65. cmd.CommandType = CommandType.StoredProcedure;
    66. SqlDataAdapter sda = new SqlDataAdapter(cmd);
    67. DataTable dt = new DataTable();
    68. sda.Fill(dt);
    69. return dt;
    70. }
    71. }
  3. Open your BAL_user_operation.cs File and code it like the following:
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. using System.Data;
    6. using System.Data.SqlClient;
    7. /// <summary>
    8. /// Summary description for BAL_user_operation
    9. /// </summary>
    10. public class BAL_user_operation
    11. {
    12. DAL_user_operation du = new DAL_user_operation();
    13. public BAL_user_operation()
    14. {
    15. //
    16. // TODO: Add constructor logic here
    17. //
    18. }
    19. public bool user_insert(string name, string email,string city)
    20. {
    21. return du.user_insert(name, email,city);
    22. }
    23. public void user_delete(int id)
    24. {
    25. du.user_delete(id);
    26. }
    27. public void user_update(string name, string email,string city, int id)
    28. {
    29. du.user_update(name, email, city, id);
    30. }
    31. public DataTable getdata()
    32. {
    33. return du.getdata();
    34. }
    35. }
  4. At last Open gridview_demo.aspx.cs file and code it like the following.
    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. public partial class _Default : System.Web.UI.Page
    8. {
    9. BAL_user_operation bu = new BAL_user_operation();
    10. protected void Page_Load(object sender, EventArgs e)
    11. {
    12. if (!Page.IsPostBack)
    13. {
    14. refreshdata();
    15. }
    16. }
    17. public void refreshdata()
    18. {
    19. GridView1.DataSource = bu.getdata();
    20. GridView1.DataBind();
    21. }
    22. protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    23. {
    24. int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
    25. bu.user_delete(id);
    26. refreshdata();
    27. }
    28. protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    29. {
    30. GridView1.EditIndex = e.NewEditIndex;
    31. refreshdata();
    32. }
    33. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    34. {
    35. TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;
    36. TextBox txtemail = GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;
    37. TextBox txtcity = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
    38. int id= Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
    39. bu.user_update(txtname.Text, txtemail.Text, txtcity.Text, id);
    40. GridView1.EditIndex = -1;
    41. refreshdata();
    42. }
    43. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    44. {
    45. GridView1.EditIndex = -1;
    46. refreshdata();
    47. }
    48. }

web.config file code

  1. <configuration>
  2. <system.web>
  3. <compilation debug="true" targetFramework="4.0" />
  4. </system.web>
  5. <connectionStrings>
  6. <add name="dbcon" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
  7. </connectionStrings>
  8. </configuration>

Output Chamber

Hope you liked this!
Have a nice day and enjoy this tutorial.