我的情况:我有3个单选按钮。单击它们时,每个显示不同的文本框,并动态创建一个按钮。我的问题是,当我单击按钮时,我失去了所有动态创建的控件。
我最终发现要在Page_Preinit上初始化动态控件,如下所示。
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
TextBox CPDT = new TextBox();
CPDT.ID = "test" + i.ToString();
CPDT.CssClass = "form-control";
Label lblCPD = new Label();
lblCPD.ID = "txtDynamiclbl" + "test" + i.ToString();
lblCPD.CssClass = "form-control-label";
lblCPD.Text = textbox[i].ToString();
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
i++;
}
Button callSoap = new Button();
callSoap.ID = "txtDynamicSearch" + servicename;
callSoap.Text = "Search";
callSoap.CssClass = ".btn-info";
callSoap.CommandArgument = "test";
callSoap.Click += new EventHandler(btnsoap);
callSoap.EnableViewState = true;
CPDPlaceHolder.Controls.Add(callSoap);
}
问题出在第一行,它只找到按钮ID,而不是文本框ID。我似乎不知道该怎么办,任何人都可以帮忙。