:::: MENU ::::

Friday, December 12, 2008

I love the asp.net validation controls. They're chick and really useful. We sometimes have to show some messages that are not the ErrorMessages of validators. An approach to do this could be to

a) ScriptManager.RegisterClientScriptBlock to show a popup (YUCK!!)

b) Put in a label and set its Text from code. This could be an option, only the error message will be in the label and not inside the ValidationSummary. This does not look good as some errors will be shown neatly in a ValidationSummary whereas others will eb shown in a separate label.

c) This is my favourite. Here's what you do:

In code behind, when you want to add a message to the ValidationSummary, just do this:

RequiredFieldValidator req = new RequiredFieldValidator();
req.ValidationGroup = "vgInput";
req.ErrorMessage = "Your message goes here.";
req.IsValid = false;
Page.Form.Controls.Add(req);
req.Visible = false;

Notice the last three lines. One causes page validation to fail, the next adds the validator to the page's controls so it can have effect (validators must be inside the form tag). The last hides the validator so the error message is shown only in the ValidationSummary and not at the location of the validator (which is at the end of the form as it's added dynamically.

Hope that helps.