有100个按钮,是一个控件数组,如何在这100个按钮的单击事件里写入相同的程序?
button[100],控件数组
我想
private void button[0]_Click(object sender, System.Windows.Forms.PaintEventArgs e)
{
  message.show “0”
}private void button[1]_Click(object sender, System.Windows.Forms.PaintEventArgs e)
{
  message.show “1”
}private void button[2]_Click(object sender, System.Windows.Forms.PaintEventArgs e)
{
  message.show “2”
}
.
.
.
private void button[99]_Click(object sender, System.Windows.Forms.PaintEventArgs e)
{
  message.show “99”
}
上面程序如何简化?谢谢!

解决方案 »

  1.   

    很简单,在一个事件中,判断sender==button[i]
    来判断按钮
      

  2.   

    动态添加控件,动态添加事件,动态修改属性,如下所示: private void Form1_Load(object sender, System.EventArgs e)
    {
    // button1
    // 
    for(int i=0,count=5;i<count;i++)//count为你要添加的控件总数
    {
    Button[] arrayBtn=new Button[5];
    Button temBtn=new Button();
    arrayBtn[i]= temBtn; this.Controls.Add(arrayBtn[i]);
    arrayBtn[i].Location = new System.Drawing.Point(96, 96+i*25);
    arrayBtn[i].Name = "button"+Convert.ToString(i);
    arrayBtn[i].TabIndex = 0;
    arrayBtn[i].Text = "button"+Convert.ToString(i); arrayBtn[i].Click += new System.EventHandler(this.buttonAll_Click); }
    } private void buttonAll_Click(object sender, System.EventArgs e)
    { MessageBox.Show("hello world");//此处还可以根据sender来进行复杂的判断
    }
      

  3.   

    利用oncommand事件。对每一个按钮赋commandname属性。比如CommandName="1"。
    在oncommand事件中
    if(e.CommandName =="1")
    //处理内容
    if(e.CommandName=="2")
    //处理内容将所有的内容关连到同一个command处理函数
      

  4.   

    tajlolo(tajlolo) ( ) 的答案正确。angeltimes(肖凡)  我还没有验证。验证后 给分。
    谢谢大家!
    请大家不用回答了。
      

  5.   

    你可以使用100个控件的事件引用到同一个事件函数之中,然后通过Sender来判断是哪个控件的事件,这样才能突出控件数组的便捷通过Sender来识别来自于哪个控件的事件可以通过使用控件的Tag属性来完成
      

  6.   

    让数组里的控件都响应同一个相应的事件,通过起在数组里唯一的标识,再将他们加以区分。下面一个例子,使5个textBox响应同一个keypress事件。          自定义一个控件事件-- textBox_KeyPress ,代码如下:          private void textBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
              {
                      TextBox box = (TextBox)sender;
       
                      MessageBox.Show(this,"you choose " + box.Name + " and you keypress " + e.KeyChar.ToString() ,"try" ,MessageBoxButtons.OK );
              }          选定textBox1,按F4显示其属性页,选择"Events"按钮(就是那个小闪电),列出了textBox1的所有事件,在keypress里写我们想让他相应的事件的名字--textBox_KeyPress,这样,当textBox1产生keypress事件时,他相应的是textBox_KeyPress这个我们自定义的事件。同样,对其它的textBox控件也做如上的属性设置。这样,5个textBox同时响应一个keypress事件,而可以通过object sender的不同,可以加以区分。这样就达到了数组的效果。大家好快啊!