HeartattacK

Putting Messages Into a ValidationSummary Control...From Code

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.

Comments

rascunho » Blog Archive » links for 2008-12-12 said:

Pingback from  rascunho  » Blog Archive   » links for 2008-12-12

# December 12, 2008 3:07 PM

Kris gore said:

Awesome.

# February 5, 2009 9:23 AM

adssd said:

ha ha haaaaa he eh heh heeh ee

# February 13, 2009 7:30 AM

propecia said:

I rarely comment on blogs but yours I had to stop and say Great Blog!!

# June 6, 2009 3:31 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)