动态生成Buttong控件后,如何在参数的传递中调用相应的单击事件。请各位大侠帮忙!

解决方案 »

  1.   

    手动加就行
    this.button1.Click += new EventHandler(button1_Click);
      

  2.   

    1 你可以加一个时间 对参数  进行判断
     private void button_Click(object sender, EventArgs e)
            {
                Button _Button = (Button)sender;            MessageBox.Show(_Button.Text);           
            }2 或则 你先定义好事件     EventHandler _Event1 = new EventHandler(button1_Click);
                EventHandler _Event2 = new EventHandler(button2_Click);            for (int i = 0; i != 2; i++)
                {
                    Button _Button = new Button();
                    _Button.Size = new Size(100, 100);
                    _Button.Location = new Point(0, i * 100);                if (i == 0)
                    {
                        _Button.Click += _Event1;
                    }
                    else
                    {
                        _Button.Click += _Event2;
                    }
                    this.Controls.Add(_Button);
                    _Button.BringToFront();
                }
             
      

  3.   

    2楼:
       因为事先不知会动态生成几个Button控件,所以怎么能事先定义好事件呢。请再说的详细点。
      

  4.   


    2楼说得很详细了,其实就是这句this.button1.Click += new EventHandler(button1_Click);把事件和事件处理方法关联起来。每生成一个控件,就需要关联它的事件和事件处理方法。
            /// <summary>
            /// 给控件事件添加处理方法
            /// </summary>
            public static void AddClickFunction(System.Windows.Forms.Control.ControlCollection Controls)
            {
                foreach (Control control in Controls)
                {
                 if (control.GetType().ToString() == "System.Windows.Forms.Button")
                        {
                            Button lb = new Button();
                            lb = (Button)control;
                            lb.Click+=事件处理方法;
                        }
                    }
                }
            }
      

  5.   

    你可以添加一个Button就给它加一个Click事件呀,那样不是可以需要了。
    既然不知道添加多少,那这些Button的事件应该有所相似的,可以通过变量传递嘛。
      

  6.   


    多个button 可以绑定到同一个方法,你可以设置一个标志,根据标志的不同就可以知道执行那个事件。
      

  7.   

    引用 3 楼 lihaiying616 的回复:
    2楼: 
      因为事先不知会动态生成几个Button控件,所以怎么能事先定义好事件呢。请再说的详细点。 
     2楼说得很详细了,其实就是这句this.button1.Click += new EventHandler(button1_Click);把事件和事件处理方法关联起来。每生成一个控件,就需要关联它的事件和事件处理方法。 
            /// <summary> 
            /// 给控件事件添加处理方法 
            /// </summary> 
            public static void AddClickFunction(System.Windows.Forms.Control.ControlCollection Controls) 
            { 
                foreach (Control control in Controls) 
                { 
                if (control.GetType().ToString() == "System.Windows.Forms.Button") 
                        { 
                            Button lb = new Button(); 
                            lb = (Button)control; 
                            lb.Click+=事件处理方法; 
                        } 
                    } 
                } 
            }
    -----------------------------------------------------