gpt4 book ai didi

c# - 查找控件()不工作

转载 作者:行者123 更新时间:2023-11-30 14:33:48 25 4
gpt4 key购买 nike

我在按钮点击事件中创建了 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;

}

谁能告诉我解决这个问题的方法?

最佳答案

你的问题是FindControl不会递归控制树。它只直接在 ControlCollection 中搜索控件容器。

This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.

您需要编写一个递归的 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;
}

关于c# - 查找控件()不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15433311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com