子动态链接未触发

本文关键字:链接 动态 | 更新日期: 2023-09-27 18:18:36

using System;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 20; i++)
        {
            Button bt = new Button();
            bt.Text = ""+i;
            bt.Click += new EventHandler(bt_Click);
            Panel1.Controls.Add(bt);
        }    
    }
    public void bt_Click(object sender, EventArgs e) 
    {
        Button selected = sender as Button;
        Panel1.Visible = false;
        Label lbl = new Label();
        lbl.Text = "i am lable";
        Panel2.Controls.Add(lbl);
        for (int i = 1; i < 30; i++)
        {                
            Button pb = new Button();    
            pb.Text = selected.Text;    
            pb.Click += new EventHandler(pb_Click);                               
            Panel2.Controls.Add(pb);               
        }
    }
    public void pb_Click(object sender, EventArgs e) // how to trigger it 
    {
        Response.Redirect("http://www.google.com");
    }         
}

this pb_Click没有触发;大家有什么想法吗

子动态链接未触发

显然pb_Click不会执行。您正在添加控件(按钮)到bt_Click处理程序将在下次提交时删除。你必须使用Page_Load事件来动态添加控件。

你可以这样写/设计你的代码:(一个技巧)

 protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 20; i++)
        {
            Button bt = new Button();
            bt.Text = "" + i;
            bt.ID = "btn" + i; // Assign unique ID
            bt.Click += new EventHandler(bt_Click);
            Panel1.Controls.Add(bt);
        }
        AddButtons();
    }
    public void bt_Click(object sender, EventArgs e)
    {
        ViewState["btnId"] = (sender as Button).ID ;
        AddButtons();
    }
    public void AddButtons()
    {
        if (ViewState["btnId"] == null)
            return;
        Button selected = Panel1.FindControl(ViewState["btnId"].ToString()) as Button;
        Panel1.Visible = false;
        Label lbl = new Label();
        lbl.Text = "i am lable";
        Panel2.Controls.Add(lbl);
        for (int i = 1; i < 30; i++)
        {
            Button pb = new Button();
            pb.Text = selected.Text;
            pb.Click += new EventHandler(pb_Click);
            Panel2.Controls.Add(pb);
        }
    }

您需要在page_init方法中添加按钮,而不要在button click或page_load方法中添加它们