How to Add an Error Message to a ValidationSummary Programmatically

7/21/2009

For a while now I had been annoyed at the fact that there is no easy way to add an error message to a ValidationSummary control... Or at least I didn't think that there was, but it turns out that it's quite simple:

   1: RequiredFieldValidator Validator = new RequiredFieldValidator();
   2: Validator.ErrorMessage = "This is your error message";
   3: Validator.ValidationGroup = "Group1";
   4: Validator.IsValid = false;
   5: Validator.Visible = false;
   6: Page.Form.Controls.Add(Validator);

The error message and the validation group needs to be changed but basically this just creates a required field validator. It then says that the validator isn't valid and makes it invisible. However since we have a ValidationSummary object, it will show up there (assuming we set up the validation group properly). That's all there is to it. Anyway, I hope this helps out someone so you're not banging your head against a wall like I was. So try it out, leave feedback, and happy coding.



Comments