We use edit operation on our Template field to check our Validation.

Initial chamber

Step 1: Open Visual Studio 2010 and create an empty website, Give a suitable name [gridview_demo].

Step 2: In Solution Explorer you get your empty website. Add a web form, SQL Database. Follow these steps:

For Web Form:

gridview_demo (Your Empty Website) - Right Click, Add New Item, then Web Form. Name it - gridview_demo.aspx.

For SQL Server Database:

gridview_demo (Your Empty Website) - Right Click, Add New Item, then SQL Server Database. Add Database inside the App_Data_folder.

Database chamber

Step 3: Go to your Database [Database.mdf], we will create a table - tbl_Data. Go to the database.mdf - Table and Add New table. Design your table like the following:

Table - tbl_data [Don’t forget to make ID, Identity Specification as Yes]

table design

Design chamber

Step 4: Now open your gridview_demo.aspx file, where we create our design for binding and making edit operation and place our validation control.

Gridview_demo.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
  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. text-decoration: underline;
  9. }
  10. </style>
  11. </head>
  12. <body>
  13. <form id="form1" runat="server">
  14. <div>
  15. <span class="style1"><strong>Gridview Demo with DropDownlist<br />
  16. </strong></span><br />
  17. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
  18. AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" DataKeyNames="id"
  19. onrowcancelingedit="GridView1_RowCancelingEdit"
  20. onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
  21. onrowupdating="GridView1_RowUpdating" BackColor="White"
  22. BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"
  23. CellSpacing="1" GridLines="None">
  24. <Columns>
  25. <asp:TemplateField HeaderText="Name">
  26. <EditItemTemplate>
  27. <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
  28. <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ForeColor="Red" ErrorMessage="Name Field can't be blanked"></asp:RequiredFieldValidator>
  29. </EditItemTemplate>
  30. <ItemTemplate>
  31. <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
  32. </ItemTemplate>
  33. </asp:TemplateField>
  34. <asp:TemplateField HeaderText="Email">
  35. <EditItemTemplate>
  36. <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
  37. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox3" ForeColor="Red" ErrorMessage="Email Field can't be blanked"></asp:RequiredFieldValidator>
  38. </EditItemTemplate>
  39. <ItemTemplate>
  40. <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>
  41. </ItemTemplate>
  42. </asp:TemplateField>
  43. <asp:TemplateField HeaderText="Sport">
  44. <EditItemTemplate>
  45. <asp:DropDownList ID="DropDownList2" DataTextField="sport" DataValueField="sport" AppendDataBoundItems="True" runat="server"
  46. SelectedValue='<%# Bind("sport") %>'>
  47. <asp:ListItem>--Select Sport--</asp:ListItem>
  48. <asp:ListItem Value="Volleyball"></asp:ListItem>
  49. <asp:ListItem Value="Basketball"></asp:ListItem>
  50. <asp:ListItem Value="Cricket"></asp:ListItem>
  51. </asp:DropDownList>
  52. <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" InitialValue="--Select Sport--" ControlToValidate="DropDownList2" ForeColor="Red" ErrorMessage=" Sport field is required
  53. "></asp:RequiredFieldValidator>
  54. </EditItemTemplate>
  55. <ItemTemplate>
  56. <asp:Label ID="Label4" runat="server" Text='<%# Bind("sport") %>'></asp:Label>
  57. </ItemTemplate>
  58. </asp:TemplateField>
  59. </Columns>
  60. <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
  61. <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
  62. <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
  63. <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
  64. <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
  65. <SortedAscendingCellStyle BackColor="#F1F1F1" />
  66. <SortedAscendingHeaderStyle BackColor="#594B9C" />
  67. <SortedDescendingCellStyle BackColor="#CAC9C9" />
  68. <SortedDescendingHeaderStyle BackColor="#33276A" />
  69. </asp:GridView>
  70. <asp:ValidationSummary ID="ValidationSummary1" ForeColor="Red" runat="server" />
  71. </div>
  72. </form>
  73. </body>
  74. </html>
Code chamber

Step 5: Open your gridview_demo.aspx.cs and write some code so that our application starts working.
  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.SqlClient;
  8. using System.Data;
  9. public partial class _Default : System.Web.UI.Page
  10. {
  11. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
  12. protected void Page_Load(object sender, EventArgs e)
  13. {
  14. if (!Page.IsPostBack)
  15. {
  16. refreshdata();
  17. }
  18. }
  19. public void refreshdata()
  20. {
  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_RowEditing(object sender, GridViewEditEventArgs e)
  29. {
  30. GridView1.EditIndex = e.NewEditIndex;
  31. refreshdata();
  32. }
  33. protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  34. {
  35. int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
  36. SqlCommand cmd = new SqlCommand("delete from tbl_data where id = @id", con);
  37. cmd.Parameters.AddWithValue("@id", id);
  38. con.Open();
  39. cmd.ExecuteNonQuery();
  40. con.Close();
  41. refreshdata();
  42. }
  43. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  44. {
  45. GridView1.EditIndex = -1;
  46. refreshdata();
  47. }
  48. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
  49. {
  50. int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
  51. TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
  52. TextBox txtemail = GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;
  53. DropDownList drpsport = GridView1.Rows[e.RowIndex].FindControl("DropDownList2") as DropDownList;
  54. SqlCommand cmd = new SqlCommand("update tbl_data set name=@name, email=@email,sport=@sport where id =@id", con);
  55. cmd.Parameters.AddWithValue("@name", txtname.Text);
  56. cmd.Parameters.AddWithValue("@email", txtemail.Text);
  57. cmd.Parameters.AddWithValue("@sport", drpsport.SelectedItem.Text);
  58. cmd.Parameters.AddWithValue("@id", id);
  59. con.Open();
  60. cmd.ExecuteNonQuery();
  61. con.Close();
  62. refreshdata();
  63. }
  64. }
Output chamber

Output

Validation With TextBox

Validation With TextBox

Validation With Dropdownlist

Validation With Dropdownlist

Hope you liked it. Thank you for reading. Have a good day.