我正在构建一个有2个按钮的用户控件。
这是我的HTML:
<form action="#">
<div id="container" runat="server" style="text-align: center;">
<asp:Button ID="btnAdd" runat="server" Text="+" Style="margin-left: 10px; margin-right: 10px"
OnClick="btnAdd_Click" />
</div>
<input type="submit" value="test" runat="server"/>
</form>
在代码方面,我根据用户点击addBtn添加了一些新的文本框:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//clear the session values
ViewState[VIEWSTATE_NAME] = null;
ViewState[VIEWSTATE_TEXT_BOX_LIST] = null;
return;
}
Debug.Write("here");
//if there is no text box list in the session - create a new one
if (ViewState[VIEWSTATE_TEXT_BOX_LIST] != null)
textboxIds = (List<string>)ViewState[VIEWSTATE_TEXT_BOX_LIST];
//get the name of the list
if (ViewState[VIEWSTATE_NAME] != null)
Name = (string)ViewState[VIEWSTATE_NAME];
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//if there is no name - return
if (name == null)
return;
//add a new text field to the list
textboxIds.Add(name + "_" + (textboxIds.Count + 1));
//st text field id
//add the textbox list to the session
ViewState[VIEWSTATE_TEXT_BOX_LIST] = textboxIds;
//show the fields
ShowTextFields();
}
/// <summary>
/// Show all the text fields of this multiple text fields
/// </summary>
private void ShowTextFields()
{
Debug.Write("count" + textboxIds.Count);
foreach (string textBoxId in textboxIds)
{
//create textbox
TextBox textBox = new TextBox();
//create validator
RequiredFieldValidator validator = new RequiredFieldValidator();
//add textbox
textBox.ID = textBoxId;
container.Controls.Add(textBox);
container.Controls.Add(new LiteralControl("<br/>"));
//add validator
validator.ControlToValidate = textBox.ID;
validator.ErrorMessage = "Required";
container.Controls.Add(validator);
}
container.Controls.Remove(btnAdd);
container.Controls.Add(btnAdd);
}
每个添加的文本框都是必需的 - 我已经为每个文本框添加了一个验证器。
我的问题是验证器在addBtn点击中运行,而我希望它在点击时在表单提交按钮上运行...
我怎样才能将它连接起来?
答案 0 :(得分:0)
您可以使用ValidationGroup
来确定验证触发器和触发器的内容。
http://msdn.microsoft.com/en-us/library/ms227424%28v=vs.100%29.aspx
如果您希望addBtn不验证任何内容,可以将CausesValidation=false
添加到该按钮。