我试图创建应用程序来动态添加控件。我有母版页,我的 asp:Content 在这里:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="scriptManager1" runat="server">
</asp:ScriptManager>
<div style="margin: 10px">
<asp:UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="myPlaceHolder" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
<asp:Button ID="btnAdd" runat="server" Text="Add" />
单击 btnAdd 后,我想添加两个文本框。我尝试像在http://jagdeepmankotia.wordpress.com/2010/01/30/dynamically-add-controls-in-asp-net-c/中那样做
这是我的代码:
static int myCount = 1;
private TextBox[] color;
private TextBox[] text;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
color = new TextBox[myCount];
text = new TextBox[myCount];
for (int i = 0; i < myCount; i++)
{
TextBox tbColor = new TextBox();
tbColor.ID = "colorTextBox" + i.ToString();
myPlaceHolder.Controls.Add(tbColor);
color[i] = tbColor;
TextBox tbText = new TextBox();
tbText.ID = "textTextBox" + i.ToString();
myPlaceHolder.Controls.Add(tbText);
text[i] = tbText;
LiteralControl literalBreak = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak);
}
}
public Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control mycontrol = page.FindControl(ctl);
if (mycontrol is System.Web.UI.WebControls.Button)
{
control = mycontrol;
// This gives you ID of which button caused postback
break;
}
}
}
return control;
}
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
if (myControl.ClientID.ToString() == "btnAdd")
myCount = myCount + 1;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//handled in PreInit
}
当在 loap foreach 中的函数 GetPostBackControl() 中寻找我的 btnAdd 时,例如在 ctr "ctl00$MainContent$scriptManager1" 的第一次迭代中,myControl 为空......在下一次迭代中也是......所以我的函数总是返回空值。可能是什么原因?