In this article I will explain how to use ASP.Net Validators in GridView TemplateField ItemTemplate to validate ASP.Net TextBox controls
HTML Markup
The HTML Markup contains a GridView with TextBox in the TemplateField ItemTemplate and RequiredField Validators for each TextBox. Below the GridView there’s also a Button that will submit the GridView values to server. When you press the Button if any TextBox is not filled with value the RequiredField Validators will be raised.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" Text='<%# Eval("Price") %>'></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvPrice" ControlToValidate="txtPrice" runat="server"
ErrorMessage="Required" ForeColor="Red"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Text='<%# Eval("Quantity") %>'></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvQuantity" ControlToValidate="txtQuantity" runat="server"
ErrorMessage="Required" ForeColor="Red"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
Namespaces
Binding the GridView
Here I am binding GridView using a DataTable with some dummy values.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Item"), new DataColumn("Price"), new DataColumn("Quantity") });
dt.Rows.Add("Shirt");
dt.Rows.Add("Football", 299, 10);
dt.Rows.Add("Shirt", 545, 15);
dt.Rows.Add("Disc", 99, 20);
dt.Rows.Add("Watch", 200, 45);
dt.Rows.Add("Clock", 670, 97);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Demo
Downloads