[英]How to create RequiredFieldValidator at the same time as textboxes that I generated in C#?
In C# server side codes, I already successful created a textboxes based on user select how many they want to fill it out. 在C#服务器端代码中,我已经成功地根据用户选择要填充的文本框创建了一个文本框。 Now I want to created a RequiredFieldValidators to validate these textboxes I generated to ensure that the users doesn't leave the textboxes blank.
现在,我想创建一个RequiredFieldValidators来验证我生成的这些文本框,以确保用户不会将文本框留为空白。 I don't know how that work but I am sure it need to put inside foreach loop to create validators at the same time as textboxes.
我不知道它是如何工作的,但是我确定它需要放入foreach循环中以与文本框同时创建验证器。 Please help
请帮忙
C# codes, C#代码
int num = 1;
foreach(PSObject psObject in output)
{
HtmlGenericControl div = new HtmlGenericControl("div");
Label ipLabel = new Label();
ipLabel.Text = psObject + "<br/>";
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(ipLabel);
div.Controls.Add(t);
phDynamicTextBox.Controls.Add(div);
tbids.Add(t.ID);
num++;
}
Session["tbids"] = tbids;
HTML codes, HTML代码
<div id="div1" runat="server">
<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />
</div>
You just need to create RequiredFieldValidator similar to Label and TextBox control. 您只需要创建类似于Label和TextBox控件的RequiredFieldValidator。
Only difference is you need to assign TextBox's ID to ControlToValidate. 唯一的区别是您需要将TextBox的ID分配给ControlToValidate。
...
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(ipLabel);
div.Controls.Add(t);
var rfv = new RequiredFieldValidator();
rfv.ID = "RequiredFieldValidator" + num;
rfv.ControlToValidate = t.ID;
rfv.ErrorMessage = num + " is required.";
div.Controls.Add(rfv);
phDynamicTextBox.Controls.Add(div);
...
@Win Answer is correct, here is a fancy way to do it: @Win Answer是正确的,这是一种奇特的方法:
var textBoxValidator = new RequiredFieldValidator
{
ID = "textBoxValidator" + num,
ControlToValidate = t.ID,
Display = ValidatorDisplay.Dynamic,
ErrorMessage = String.Format("The TextBox field #{0} Cannot be blank", num),
ForeColor = Color.Red
};
div.Controls.Add(textBoxValidator);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.