无法获得点击按钮的索引

时间:2014-12-21 12:18:04

标签: c# winforms

我的资源图片名称为:{1.jpg,2.jpg,.............,30.jpg} 我有按钮{btn1,btn2,.............,btn30} 所有我想做的就是通过点击btn1将错误的图像1.jpg放在面板中...同样转到图像2用于btn2 ..在同一面板中btn30的图像30 这就是我在我的代码中写的......

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Button[] buttons = { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12, btn13, btn14, btn15, btn16, btn17, btn18, btn19, btn20, btn21, btn22, btn22, btn23, btn24, btn25, btn26, btn27, btn28, btn29, btn30 };

        //did this becz couldnt fill the array buttons with a for loop...hope if u know to tell me how
        for(int i=0;i<30;i++) buttons[i].Click += myEventHandler;

    }

    void myEventHandler(object sender, EventArgs e)
    { 
        Button button = sender as Button;
        for(int i=0;i<30;i++)
        {
            if (sender.Equals ////howw to get the index of the button
        }

        Bitmap b=new Bitmap(myProject.Properties.Resources  //how to apply the index of the button in getting the name of the image;
        panel2.BackgroundImage=b;
    }
}

2 个答案:

答案 0 :(得分:2)

将您的按钮保存在类中的私有列表中,并在事件处理程序中使用IndexOf。

private List<Button> buttons;

private void Form1_Load(object sender, EventArgs e)
{
    buttons = new [] { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12, btn13, btn14, btn15, btn16, btn17, btn18, btn19, btn20, btn21, btn22, btn22, btn23, btn24, btn25, btn26, btn27, btn28, btn29, btn30 }.ToList();
    buttons.ForEach(x => x.Click += myEventHandler);
}

void myEventHandler(object sender, EventArgs e)
{ 
    Button button = sender as Button;
    int idx = buttons.IndexOf(button);
}

答案 1 :(得分:0)

正如我在评论中所说,我个人会稍微重构并使用lambda表达式来调用泛型&#39; ChangeImage&#39;方法

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Button[] buttons = { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12, btn13, btn14, btn15, btn16, btn17, btn18, btn19, btn20, btn21, btn22, btn22, btn23, btn24, btn25, btn26, btn27, btn28, btn29, btn30 };

        //did this becz couldnt fill the array buttons with a for loop...hope if u know to tell me how


        for (int i = 0; i < 30; i++)
        {
            int n = i;

            buttons[i].Click += (object s, EventArgs ea) => ChangeImage(n);
        }
    }

    void ChangeImage(int id)
            {
Bitmap b=new Bitmap(myProject.Properties.Resources  //how to apply the index of the button in getting the name of the image;
                panel2.BackgroundImage=b;


            }
}

然后,您可以使用ChangeImage方法将背景变为图像,并通过id参数传入ID:)