Validation Summary Custom Message
Category: DotNet
Sometimes we want to show a custom message in a page's validation summary depending on something that happens in our business object, ie. catch an exception and display the message to the user.
First, be sure your ValidationSummary is in a Panel control. You can add the following presentation helper somewhere in your project. Basically we pass in the message we want to be displayed, ie the Exception.Message and this function will return a custom validator that we add to the Panel that contains the validation summary.
public static class PresentationHelper
{
public static CustomValidator BuildCustomValidator(string message)
{
CustomValidator CustomValidatorCtrl = new CustomValidator();
CustomValidatorCtrl.IsValid = false;
CustomValidatorCtrl.ErrorMessage = message;
CustomValidatorCtrl.Display = ValidatorDisplay.None;
return CustomValidatorCtrl;
}
}
Here is an example of usage in a Page codebehind:
protected void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
MyBusinessObject.DoSomething(...);
}
catch(Exceptions.PresentationException exc)
{
PanelCreate.Controls.Add(PresentationHelper.BuildCustomValidator(exc.Message));
}
}