This trick is especially useful when you have custom code to be executed after your form have been submitted, and still wishes to communicate an error the same way as you communicate form validation errors.
Imagine the following ValidationSummary:
<asp:ValidationSummary ID="valSummary" runat="server" DisplayMode="BulletList" ValidationGroup="ValGroup" />
Any form error is displayed in this summary. When the user clicks your submit button you process the form:
protected void btnSubmit_Click(object sender, EventArgs e) { Page.Validate(); if (Page.IsValid) { // do custom processing of form } }
But is the processing fails, is it too late to pop the validation summary? Not at all.
To do so, add a CustomValidator to your form:
<asp:CustomValidator ID="valCustom" runat="server" ValidationGroup="ValGroup" />
And simply set the error message in the CustomValidator, inside your btnSubmit_Click:
protected void btnSubmit_Click(object sender, EventArgs e) { Page.Validate(); if (Page.IsValid) { bool isOK = ProcessTheFormData(); if (!isOK) { // Optional: Update the summary with a nice header valSummary.HeaderText = "Oops something went wrong"; // Mandatory: Invalidate the custom validator, and set a error message valCustom.IsValid = false; valCustom.ErrorMessage = "A clever error message"; } } }
