代码如下:
    private void button1_Onclick(ojbect sender, System.EventArgs e)
    {
        linkbutton templinkbutton = new linkbutton();
        templinkbutton.Click += new System.EventHandler(this.templinkbutton_Click)
        panel1.Controls.Add(templinkbutton);
    }    void templinkbutton_Click(object sender, System.EventArgs e)
    {
        label1.Text = "事件触发了";
    }其中button1、panel1、label1是静态的,只有templinkbutton是动态生成的,为什么当我点击templinkbutton时却执行不到templinkbutton_Click事件?请各位大哥帮忙。

解决方案 »

  1.   

    private void button1_Onclick(ojbect sender, System.EventArgs e)
        {
            linkbutton templinkbutton = new linkbutton();        
            panel1.Controls.Add(templinkbutton);
            templinkbutton.ID = "lb1";
            templinkbutton.Click += new System.EventHandler(this.templinkbutton_Click)
        }    void templinkbutton_Click(object sender, System.EventArgs e)
        {
            label1.Text = "事件触发了";
        }
      

  2.   

    button1_Onclick已正确执行,因为当点击button1时在页面上已经显示了动态生成的控件。
      

  3.   

    you need re-create the control upon postback
    bool ButtonAdded
    {
      get
      {
    object o = ViewState["ButtonAdded"];
    if (o == null)
    return false;
    return (bool)o;
      }
      set
      {
    ViewState["ButtonAdded"]= value;
      }
    }
        void AddControl()
        {
    linkbutton templinkbutton = new linkbutton();
            templinkbutton.Click += new System.EventHandler(this.templinkbutton_Click)
            panel1.Controls.Add(templinkbutton);
        }    private void Page_Load(ojbect sender, System.EventArgs e) //make sure it hooks up Page's Load event
        {
           if (ButtonAdded)
            {
    AddControl();
    }
        }    private void button1_Onclick(ojbect sender, System.EventArgs e)
        {
    if (!ButtonAdded)
            {
    AddControl();
    ButtonAdded = true;
    }
        }    void templinkbutton_Click(object sender, System.EventArgs e)
        {
            label1.Text = "事件触发了";
        }