How to get the validator's controltovalidate attribute in ASP.NET codebehind?

时间:2016-07-11 20:24:57

标签: c# asp.net validation

In the codebehind of my page I create a list of errors instead of using the validationsummary with it's limited styling.

Here is my code I use for this:

Panel_feedback.Controls.Add(new LiteralControl("<div class='alert alert-danger alert-dismissible fade in' role='alert'>"));
Panel_feedback.Controls.Add(new LiteralControl("<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button>"));
Panel_feedback.Controls.Add(new LiteralControl("<h2>ERROR!</h2>"));
Panel_feedback.Controls.Add(new LiteralControl("<ul class='fa-ul'>"));

foreach (IValidator error in this.Validators)
  {
     if (!error.IsValid)
         Panel_feedback.Controls.Add(new LiteralControl("<li><i class='fa-li fa fa-times-circle'></i>" + error.ErrorMessage + "</li>"));
   }
Panel_feedback.Controls.Add(new LiteralControl("</ul>"));

It seems like the error object should have a property like "controltovalidate" or something, but this isn't the case. The reason I want to know what the controltovalidate target is because I want to change the border red so the user will see which textbox is wrong.

Here is an example of one of my validators:

<asp:RequiredFieldValidator ID="RequiredFieldValidator_name" runat="server" ErrorMessage="Vul uw naam in" Display="none" ControlToValidate="TextBox_name"></asp:RequiredFieldValidator>

Thanks in advance

1 个答案:

答案 0 :(得分:1)

Try casting to BaseValidator instead of IValidator, this should have more details for your needs.

See MSDN documentation

foreach (BaseValidator error in this.Validators)
{
    if (error.IsValid)
        continue;

    Panel_feedback.Controls.Add(new LiteralControl("<li><i class='fa-li fa fa-times-circle'></i>" + error.ErrorMessage + "</li>"));
    string failedControlID = error.ControlToValidate;
    // ...
}