Use Validation Inside GridView In ASP.NET

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.   
  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.             text-decoration: underline;  
  11.         }  
  12.     </style>  
  13. </head>  
  14. <body>  
  15.     <form id="form1" runat="server">  
  16.     <div>  
  17.       
  18.         <span class="style1"><strong>Gridview Demo with DropDownlist<br />  
  19.         </strong></span><br />  
  20.       
  21.         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"   
  22.             AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" DataKeyNames="id"   
  23.             onrowcancelingedit="GridView1_RowCancelingEdit"   
  24.             onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"   
  25.             onrowupdating="GridView1_RowUpdating" BackColor="White"   
  26.             BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"   
  27.             CellSpacing="1" GridLines="None">  
  28.             <Columns>  
  29.                 <asp:TemplateField HeaderText="Name">  
  30.                     <EditItemTemplate>  
  31.                         <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>  
  32.                         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ForeColor="Red" ErrorMessage="Name Field can't be blanked"></asp:RequiredFieldValidator>  
  33.                     </EditItemTemplate>  
  34.                     <ItemTemplate>  
  35.                         <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>  
  36.                     </ItemTemplate>  
  37.                 </asp:TemplateField>  
  38.                 <asp:TemplateField HeaderText="Email">  
  39.                     <EditItemTemplate>  
  40.                         <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>  
  41.                          <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox3" ForeColor="Red" ErrorMessage="Email Field can't be blanked"></asp:RequiredFieldValidator>  
  42.                     </EditItemTemplate>  
  43.                     <ItemTemplate>  
  44.                         <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>  
  45.                     </ItemTemplate>  
  46.                 </asp:TemplateField>  
  47.                 <asp:TemplateField HeaderText="Sport">  
  48.                     <EditItemTemplate>  
  49.                         <asp:DropDownList ID="DropDownList2" DataTextField="sport" DataValueField="sport" AppendDataBoundItems="True" runat="server"   
  50.                             SelectedValue='<%# Bind("sport") %>'>                           
  51.                             <asp:ListItem>--Select Sport--</asp:ListItem>  
  52.                             
  53.                             <asp:ListItem Value="Volleyball"></asp:ListItem>  
  54.                              <asp:ListItem Value="Basketball"></asp:ListItem>  
  55.                                <asp:ListItem Value="Cricket"></asp:ListItem>                                                   
  56.                         </asp:DropDownList>  
  57.                          <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" InitialValue="--Select Sport--" ControlToValidate="DropDownList2" ForeColor="Red" ErrorMessage=" Sport field is required  
  58.  "></asp:RequiredFieldValidator>  
  59.                     </EditItemTemplate>  
  60.                     <ItemTemplate>  
  61.                         <asp:Label ID="Label4" runat="server" Text='<%# Bind("sport") %>'></asp:Label>  
  62.                     </ItemTemplate>  
  63.                 </asp:TemplateField>  
  64.             </Columns>  
  65.             <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />  
  66.             <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />  
  67.             <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />  
  68.             <RowStyle BackColor="#DEDFDE" ForeColor="Black" />  
  69.             <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />  
  70.             <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  71.             <SortedAscendingHeaderStyle BackColor="#594B9C" />  
  72.             <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  73.             <SortedDescendingHeaderStyle BackColor="#33276A" />  
  74.         </asp:GridView>  
  75.         <asp:ValidationSummary ID="ValidationSummary1" ForeColor="Red" runat="server" />  
  76.       
  77.     </div>  
  78.     </form>  
  79. </body>  
  80. </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.   
  10. public partial class _Default : System.Web.UI.Page  
  11. {  
  12.     SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.   
  16.         if (!Page.IsPostBack)  
  17.         {  
  18.             refreshdata();  
  19.         }  
  20.   
  21.     }  
  22.   
  23.     public void refreshdata()  
  24.     {     
  25.         SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  26.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  27.         DataTable dt = new DataTable();  
  28.         sda.Fill(dt);  
  29.         GridView1.DataSource = dt;  
  30.         GridView1.DataBind();  
  31.   
  32.   
  33.     }  
  34.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  35.     {  
  36.         GridView1.EditIndex = e.NewEditIndex;  
  37.         refreshdata();  
  38.     }  
  39.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  40.     {  
  41.         int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());  
  42.         SqlCommand cmd = new SqlCommand("delete from tbl_data where id = @id", con);  
  43.         cmd.Parameters.AddWithValue("@id", id);  
  44.         con.Open();  
  45.         cmd.ExecuteNonQuery();  
  46.         con.Close();  
  47.         refreshdata();  
  48.   
  49.     }  
  50.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  51.     {  
  52.         GridView1.EditIndex = -1;  
  53.         refreshdata();  
  54.     }  
  55.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  56.     {  
  57.         int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());  
  58.         TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox2"as TextBox;  
  59.         TextBox txtemail = GridView1.Rows[e.RowIndex].FindControl("TextBox3"as TextBox;  
  60.         DropDownList drpsport = GridView1.Rows[e.RowIndex].FindControl("DropDownList2"as DropDownList;  
  61.         
  62.         SqlCommand cmd = new SqlCommand("update tbl_data set name=@name, email=@email,sport=@sport where id =@id", con);  
  63.         cmd.Parameters.AddWithValue("@name", txtname.Text);  
  64.         cmd.Parameters.AddWithValue("@email", txtemail.Text);  
  65.         cmd.Parameters.AddWithValue("@sport", drpsport.SelectedItem.Text);  
  66.         cmd.Parameters.AddWithValue("@id", id);  
  67.         con.Open();  
  68.         cmd.ExecuteNonQuery();  
  69.         con.Close();  
  70.         refreshdata();        
  71.             
  72.   
  73.     }  
  74.       
  75. }  
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.

 

Up Next
    Ebook Download
    View all
    Learn
    View all