子动态链接没有触发

时间:2011-12-23 09:43:33

标签: c#

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");
    }         
}

这个pb_Click没有触发;所以,任何想法

2 个答案:

答案 0 :(得分:3)

显然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);

        }
    }

答案 1 :(得分:1)

您需要在page_init方法中添加按钮,不要在按钮单击或page_load方法中添加它们。