![](/img/trans.png)
[英]How to add RequiredFieldValidator control with ValidationExpression in code behind?
[英]Add RequiredFieldValidator to dynamically created control in code behind
我的頁面上有一些文本框。 一些ASP:Textbox是在.aspx文件中創建的,而其他一些自定義文本框則是在代碼隱藏(基於db)中創建的。 我想驗證以確保所有字段都已填寫。
當我按ASP:Button繼續時,將正確驗證在html / aspx文件中創建的文本框,但是由於某些原因,將忽略動態創建的RequiredFieldValidators。
碼:
<tr runat="server" id="weight_row">
<td>
Weight: <asp:Label runat="server" ID="weightReqLabel" CssClass="required" Visible="false">*</asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="weight" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="validator_weight" ControlToValidate="weight" SetFocusOnError="true" ErrorMessage="Required." CssClass="validation-error"></asp:RequiredFieldValidator>
</td>
</tr>
上面的工作正常。
但是,這不起作用:
TextBox txtbx = new TextBox();
txtbx.ID = "TextBox_" + i;
txtbx.CssClass = "form-control";
txtbx.Text = fieldValue;
RequiredFieldValidator reqFieldVal = new RequiredFieldValidator();
reqFieldVal.ID = "validator_" + i;
reqFieldVal.ControlToValidate = txtbx.ID;
reqFieldVal.SetFocusOnError = true;
reqFieldVal.ErrorMessage = "Required";
reqFieldVal.EnableClientScript = false;
reqFieldVal.CssClass = "required";
reqFieldVal.Enabled = true;
placeHolder.Controls.Add(txtbx);
placeHolder.Controls.Add(reqFieldVal);
在添加EnableClientScript=false
之前,沒有任何驗證有效。 在我添加了這些之后,通常編碼的驗證器起作用了,但是后面的代碼沒有起作用。
我也嘗試添加ValidationGroup並嘗試在按鈕的OnClick中使用Page.Validate,但這似乎無濟於事。
protected void SaveAndContinue_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
((Redirect))
}
}
我究竟做錯了什么?
嘗試這個
...
placeHolder.Controls.Add(reqFieldVal);
reqFieldVal.Validate();
...
它對我有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.