1

I have a Button array in C# WFA and I want to create an event for a click of any button in the array. How can I do it? And how to know which location in the array it is? I know sender is the button itself

3 Answers 3

6

You can use a for loop that closes over a variable containing the current index:

for(int i = 0; i < buttons.Length; i++)
{
    //it's important to have this; closing over the loop variable would be bad
    int index = i;  
    buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you.I just want to know, what is the last row? I know what its doing, just want to know how does it called so i can learn it.
It is creating an anonymous method; this particular syntax is called a lambda expression.
3

You can add the event handler to each button in a for loop.

Inside the handler, you can call array.IndexOf((Button)sender).

Comments

0

try this

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

        Button[] myButtons = new Button[10];
        private void Form1_Load(object sender, EventArgs e)
        {

            for(int i = 0; i < myButtons.Length; i++)
            {
                int index = i;
                this.myButtons[i] = new Button();

                this.myButtons[i].Location = new System.Drawing.Point(((i + 1) * 70), 100 + ((i + 10) * 5));
                this.myButtons[i].Name = "button" + (index + 1);
                this.myButtons[i].Size = new System.Drawing.Size(70, 23);
                this.myButtons[i].TabIndex = i;
                this.myButtons[i].Text = "button" + (index + 1);
                this.myButtons[i].UseVisualStyleBackColor = true;
                this.myButtons[i].Visible = true;

                myButtons[i].Click += (sender1, ex) => this.Display(index+1);

                this.Controls.Add(myButtons[i]);
            }
        }

        public void Display(int i)
        {
            MessageBox.Show("Button No " + i);
        }

    }
}

2 Comments

This would not compile. Display is not of the proper syntax, and you're invoking the method in the for loop, not creating a delegate from it.
how do I add an image to the button this method worked for me, and I am now trying to add an image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.