views:

74

answers:

2

It it possible to enable validation in an ASP.NET GridView purely declaratively?

What I've tried:

  • A GridView bound to an ObjectDataSource with SelectMethod and UpdateMethod defined

  • The GridView contains some ReadOnly BoundField columns and a TemplateField whose EditTemplate contains a TextBox and a RegularExpressionValidator that only allows numeric input in the TextBox.

  • The GridView also contains a CommandField with ShowEditButton=true and CausesValidation=true.

If I click on Edit, enter an invalid value, then click on Save, there is a PostBack, and an exception is thrown in the server (Input string was not in a correct format).

I can of course avoid this by adding validation code to the RowUpdating event handler on the server (see below), but is there any declarative way to force the validation to be done without adding this code?

protected void MyGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Page.Validate("MyValidationGroup");
    if (!Page.IsValid)
    {
        e.Cancel = true;
    }
}
A: 

Are your validators in the EditItemTemplate?

TheGeekYouNeed
A: 

You need that code.

"In addition to relying on client side validation, it is also important that you call Page.IsValid when handling the postback event."

http://weblogs.asp.net/rajbk/archive/2007/03/15/page-isvalid-and-validate.aspx

update

To avoid boiler plate code, you could have all pages inherit from a base class and all user controls inherit from a different base class. The base class will have the common logic (like the one above). You then have to either manually wire it up or walk through the control tree and automatically wire up the events.

I would personally stick with what you currently have though.

Raj Kaimal
I understand that server-side validation is necessary, my question was whether it can be enabled declaratively. I'm trying to reduce the amount of identical boilerplate code that needs to be added.However I suspect you're right: GridView and similar classes don't have a "ValidationGroup" property, and without this they wouldn't know what needs to be validated.
Joe