开发者

Set "text" property to a CustomValidator in ASP.NET (Webforms)

In my .aspx page, I've a ValidationSummary where I put error messages returned by my Business Layer.

The error messages appears in the summary, ok, but not the "*" that normally appears next to the field =(

In the code behind, I've the following code:

CustomValidator cv = new Custo开发者_开发技巧mValidator();
cv.ControlToValidate = field.ID;
cv.ErrorMessage = "Error Message";
cv.Text = "*";
cv.IsValid = false;
Page.Validators.Add(cv);

Basically, I want to add the "*" next to each incorrect field, but without creating CustomValidators for each one... is it possible?


The ErrorMessage property will be displayed in the ValidationSummary while the Text property will be displayed where the Validator is. To meet your requirement, you need to put the CustomValidators beside those controls you want to validate.

Since all the validators are generated in code behind, you need to add those validators to a proper position using Page.Controls.AddAt(int indexer, Control child) because CustomValidator is also a control.

When you add the validator beside the textbox, you can get the exact index by following code.

<form id="form1" runat="server">
    <asp:TextBox ID="tb" runat="server"></asp:TextBox>
    <asp:Button runat="server" Text="just a post back" />
</form>

protected void Page_Load(object sender, EventArgs e)
{
     CustomValidator v = new CustomValidator();
     v.ErrorMessage = "error!";
     v.Text = "****";
     v.ControlToValidate = "tb";
     int index = form1.Controls.IndexOf(tb);
     form1.Controls.AddAt(index + 1, v);
}

NOTE: if you put the textbox in a PlaceHolder or some containers, you can't get it by form1.Controls because Container.Controls returns the 1st level child controls only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜