/// <summary>
/// Daniel Balla's Weblog - Various posts
/// on .NET Development, ASP.NET, Agile,
/// TDD, Architecture, SQL and others.
/// </summary>
[Serializable]
class Blog<T> where T : ASP.NET, Ajax, WCF, WF, new()
{
}
Friday, March 23, 2007
Row level validation in a gridview
A couple days ago a friend asked me how can you make the ASP.NET validators validate the contents of a gridview at row level, so that each row works independently. For example, in the grid below use a requiredfieldvalidator on each row so that the Save button would validate the description textbox on the same row, but wouldn’t validate any of the other rows’ descriptions.

In this case, clicking the save button in the “Dairy products” row would cause the validation to suppress the postback, but clicking the save button of any other row wouldn’t.
The solution is simple: use the validation group bound to a unique row identifier. In our example (which displays the contents of the Categories table of the Northwind database) the binding would look like:
(asp:TextBox Width="300px" ID="txtDescription" runat="server" Text='(%# Bind("Description") %)' /)
(asp:RequiredFieldValidator ID="reqDescription" runat="server" ControlToValidate="txtDescription" ErrorMessage="*" ValidationGroup='(%# Bind("CategoryID") %)' /)
(asp:Button ID="butSave" runat="server" Text="Save" ValidationGroup='(%# Bind("CategoryID") %)' /)
The parenthesis ( ) should be replaced with less-greater than signs < >, they are just a workaround the poor blogger’s editor.
Download sample

In this case, clicking the save button in the “Dairy products” row would cause the validation to suppress the postback, but clicking the save button of any other row wouldn’t.
The solution is simple: use the validation group bound to a unique row identifier. In our example (which displays the contents of the Categories table of the Northwind database) the binding would look like:
(asp:RequiredFieldValidator ID="reqDescription" runat="server" ControlToValidate="txtDescription" ErrorMessage="*" ValidationGroup='(%# Bind("CategoryID") %)' /)
(asp:Button ID="butSave" runat="server" Text="Save" ValidationGroup='(%# Bind("CategoryID") %)' /)
The parenthesis ( ) should be replaced with less-greater than signs < >, they are just a workaround the poor blogger’s editor.
Download sample
Labels: ASP.NET

2 Comments:
Thank you! It has helped me much!
Mónica (Argentine)
By
Pato, at Tuesday, June 10, 2008 2:06:00 PM BST
Thank you! It has helped me much!
Mónica from Argentine
By
Anonymous, at Tuesday, June 10, 2008 2:07:00 PM BST
Post a Comment
<< Home