3

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

}

任何人都可以告诉我解决这个问题的方法吗?

4

2 回答 2

5

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

只有当控件直接包含在指定容器中时,此方法才会找到控件;也就是说,该方法不会在控件内的控件层次结构中进行搜索。

您需要编写一个递归 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;
}
于 2013-03-15T13:23:00.730 回答
2

试试这个代码.....

protected void Page_Load(object sender, EventArgs e)
    {

        if (IsPostBack)
        {
            createcontrol();
        }
    }
private void createcontrol()
    {

        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);
            plh1.Controls.Add(tr);
        }
    }
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].ToString();
        TextBox txt = new TextBox();
        txt = plh1.FindControl("txt_" + identity) as TextBox;
        string q = txt.Text;

    }
 protected void Button1_Click(object sender, EventArgs e)
    {
        createcontrol();
}
于 2013-03-15T13:45:29.387 回答