我有一个用户控件,包含很少的服务器控件,如文本框和下拉列表。
我还添加了一些必需的字段验证控件。通常,如果我在设计时添加用户控件,这些验证工作正常。
但是当我动态添加用户控件时,验证控件就不起作用而页面会被回发。
用户控制:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="myUserControl.ascx.cs" Inherits="myUserControl" %>
<table cellpadding="0" cellspacing="0" >
<tr>
<td>
<asp:TextBox runat="server" ID="txtLastName" Width="80px" MaxLength="64" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtLastName" runat="server" ErrorMessage="Required Value" Display="None"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server" TargetControlID="RequiredFieldValidator1"></ajaxToolkit:ValidatorCalloutExtender>
</td>
<td>
<asp:TextBox runat="server" ID="txtFirstName" Width="80px" MaxLength="64" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtFirstName" runat="server" ErrorMessage="Required Value" Display="None"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server" TargetControlID="RequiredFieldValidator2"></ajaxToolkit:ValidatorCalloutExtender>
</td>
<td>
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="DeleteButton_Click" CausesValidation="false" />
</td>
</tr>
</table>
包含表单标记:
<form id="form1" runat="server">
<div>
<div align="right" ><asp:Button ID="btnAdd" runat="server" Text="Add Order Line" onclick="btnAdd_Click" CausesValidation="false" /></div>
<asp:PlaceHolder runat="server" ID="DynamicNameList" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</div>
</form>
包含表单代码:
public partial class WebForm1 : System.Web.UI.Page, IDynamicControlContainer
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (string id in LoadControlIdList())
{
Create(id);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Create(null);
}
public void Create(string id)
{
string targetId = id ?? Guid.NewGuid().ToString();
myUserControl control = LoadControl("~/CustomControls/myUserControl.ascx") as myUserControl;
control.ID = targetId;
DynamicNameList.Controls.Add(control);
SaveControlIdList();
}
public void Delete(Control control)
{
DynamicNameList.Controls.Remove(control);
SaveControlIdList();
}
public void SaveControlIdList()
{
List<string> idList = new List<string>();
foreach (Control control in DynamicNameList.Controls)
{
idList.Add(control.ID);
}
ViewState["IdList"] = idList;
}
public string[] LoadControlIdList()
{
var list = (List<string>)ViewState["IdList"];
if (list == null)
{
return new string[0];
}
return list.ToArray();
}
}
public interface IDynamicControlContainer
{
/// <summary>
/// Deletes the specified control from the container
/// </summary>
/// <param name="control">The control.</param>
void Delete(Control control);
}
}
答案 0 :(得分:0)
您需要使用Page_Init或CreateChildControls事件来执行此操作。在Page_Load启动时,控制树已经加载。