Thursday, August 11, 2005

 

CustomValidator in a TemplateColumn of a DataGrid

I had a DataGrid with a TemplateColumn that had a TextBox in the ItemTemplate (not the EditItemTemplate) so that the user can easily enter text in for all of the rows without having to click an Edit and Update link for each one. The problem I had was with validation of this data. I had to use a CustomValidator, but the challenge was to specify the function on the server side that would do the validation. Because I am using Visual Studio, I am designing these pages with a code-behind page. This made the compiler throw a fit if I added an OnServerValidate attribute to the CustomValidator.

The solution that I found was to add another CustomValidator to the page (not inside the DataGrid). This CustomValidator had a blank ErrorMessage and Text property and its Display was set to None. However, it will still be enabled and cause its ServerValidate method to run. I call this validator my trigger validator.

The trigger validator's ServerValidate method is simple. It just loops through each of the items in the DataGrid, finds the TextBox's validator, adds a handler to the appropriate validate function, and then calls the Validate method for each one. Here's the code for the trigger validator:
Private Sub MyValidatorTrigger_ServerValidate(ByVal source _
As System.Object, ByVal args As _
System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles MyValidatorTrigger.ServerValidate

Dim MyValidator As CustomValidator
For Each dgi As DataGridItem In MyDataGrid.Items
MyValidator = dgi.FindControl("MyValidator")
AddHandler MyValidator.ServerValidate, AddressOf MyValidator_ServerValidate
MyValidator.Validate()
Next
args.IsValid = True
End Sub

Then I just write the MyValidator_ServerValidate to validate the TextBox the way I want. In that method, the TextBox is found by using the source.NamingContainer.FindControl method.

The result of this is that each TextBox with an error gets a * (Text property) put beside it if the validation fails. I like the fact that the ErrorMessage is displayed multiple times, once for each offending TextBox. Though, it may be desired sometimes to just show one error message (from the trigger) and multiple *'s.

Note also that the CustomValidator does not have a ControlToValidate property set, so that the validator will run even if the TextBox is blank.
Comments:
Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?