RexMan85
RexMan85

Reputation: 59

Adding events to code-created objects

I am creating a 2d array of buttons using code and I want to add a button_click() method. Besides the 2 usual arguments (object sender, EventArgs e) I want to get as an input 2 more variables, To identify which button was clicked, and do something else as a result.

I am currently doing this

 arr[i,j].Click+= new EventHandler(button_click);
 public void button_click(object sender, EventArgs e)

Is there another way of adding events that will allow me to do what I want?

And on a seperate note. Is there an easy way of creating cubes with a certain color without using buttons?

Upvotes: 0

Views: 44

Answers (2)

gmail user
gmail user

Reputation: 2783

Create a class which inherits from button class. And add 2 properties to it. Then access those properties in your form . Following example is one way to solve your problem.

public class ButtonCtrl : Button
{
    public ButtonCtrl(int _arg1, int _arg2)
    {
        Arg1 = _arg1;
        Arg2 = _arg2;
    }

    public int Arg1 { get; set; }
    public int Arg2 { get; set; }         
}

//create buttons in form c'tor

    public Form1()
    {
        InitializeComponent();

        ButtonCtrl button1 = new ButtonCtrl(1,2);
        button1.Text = "dynamic 1";
        button1.Click += new EventHandler(button_click);
        button1.Top = 10;
        this.Controls.Add(button1);

        ButtonCtrl button2 = new ButtonCtrl(3, 4);
        button2.Text = "dynamic 2";
        button2.Click += new EventHandler(button_click);
        button2.Top = 30;
        this.Controls.Add(button2);

    }

And the event handler

    public void button_click(object sender,EventArgs e)
    {
        if(sender is ButtonCtrl)
        {
            ButtonCtrl btnCtrl= sender as ButtonCtrl;
            label1.Text = btnCtrl.Arg1.ToString() + " " + btnCtrl.Arg2.ToString();
        }
    }

Upvotes: 0

AlexD
AlexD

Reputation: 32576

To identify which button was clicked, and do something else as a result.

You could use sender parameter to identify the button which was clicked.

If you do not want to introduce a custom button type which would have properties for i and j, you could use Tag property to store the indices.

Upvotes: 1

Related Questions