我在按钮单击事件中创建了 5 个文本框,当单击动态生成的按钮时,我必须获取文本框中的值。
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<5;i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl tdbtn = new HtmlGenericControl("td");
TextBox txt=new TextBox();
txt.ID="txt_"+i.ToString();
td.Controls.Add(txt);
Button btn=new Button();
btn.ID="btn_"+i.ToString();
btn.Click+=new EventHandler(btnpay_Click);
btn.Text="Pay";
tdbtn.Controls.Add(btn);
tr.Controls.Add(td);
tr.Controls.Add(tdbtn);
PlaceHolder1.Controls.Add(tr);
}
}
但我无法在文本框中获取值btnpay_Click
protected void btnpay_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn = sender as Button;
string[] splitvaues = btn.ID.Split('_');
string identity = splitvaues[1];
TextBox txt = new TextBox();
txt =PlaceHolder1.FindControl("txt_" + identity) as TextBox;
}
谁能告诉我解决这个问题的方法吗?
你的问题是查找控件 http://msdn.microsoft.com/en-us/library/486wc64h.aspx不会在控制树中递归。它只直接在控制集合 http://msdn.microsoft.com/en-us/library/system.web.ui.controlcollection.aspx容器的。
仅当该控件直接存在时,此方法才会查找该控件
由指明容器盛装;也就是说,该方法不
在控件内的控件层次结构中进行搜索。
您需要编写一个递归FindControl。就像是:
public static Control FindControlRecursive(this Control control, string id)
{
if (control == null || control.ID == id) return control;
foreach (var c in control.Controls)
{
var found = c.FindControlRecursive(id);
if (found != null) return found;
}
return null;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)