Two questions:
On postback when a user clicks submit, how can I add a error message to validation summary?
Is it also possible to highlight a particular textbox using the built in .net validation controls?
Two questions:
On postback when a user clicks submit, how can I add a error message to validation summary?
Is it also possible to highlight a particular textbox using the built in .net validation controls?
Add a custom validator and manually set it's IsValid and ErrorMessage properties. Sort of like this:
<asp:panel ID="ErrorsPanel" runat="server" CssClass="ErrorSummary">
<asp:CustomValidator id="CustomValidator1" runat="server"
Display="None" EnableClientScript="False"></asp:CustomValidator>
<asp:ValidationSummary id="ErrorSummary" runat="server"
HeaderText="Errors occurred:"></asp:ValidationSummary>
</asp:panel>
In the code behind:
//
// Update the database with the changes
//
string ErrorDetails;
if (!Db.Update(out ErrorDetails))
{
CustomValidator1.IsValid = false;
CustomValidator1.ErrorMessage = ErrorDetails;
}
To add error message on validation summary you can use EnableClientScript property of ValidationSummary and the other validation controls. Set EnableClientScript to false all of them :
<asp:ValidationSummary
HeaderText="You must enter a value in the following fields :"
DisplayMode="BulletList"
EnableClientScript="false"
runat="server"/>
For highlighting a control, no it's not possible with current controls.
But I put my validation controls near the related controls, and I set their Text property as "*". Then if the validation fails, it appears near failed control.
Maybe you can use custom validator to highlight the failed control. But you should write your own implementation.
Here is a version of the above answers that is an extension method for ValidationSummary, which takes care of the validation group ID.
public static void AddCustomMessage(this ValidationSummary summaryControl, string message)
{
summaryControl.Page.Validators.Add(new CustomValidator {
ValidationGroup = summaryControl.ValidationGroup,
ErrorMessage = message,
IsValid = false
});
}