Control Arrays in .NET

Back in the day when I dabbled briefly in VB6, creating an array of controls was pretty straight forward and it was something that I found hard to adjust to when I moved across to .NET. It’s actually very easy, I’ll show you…

Start a new Winforms project and drop a button on a form, then copy and paste the following code into the button’s click event:

private void button1_Click(object sender, EventArgs e)
{
    int numBtns = 5;   //number of buttons to create.

    for (int i = 0; i < numBtns; i++)
    {
        Button btns = new Button();
        btns.Size = button1.Size;
        btns.Location = new Point(0, 0 + btns.Height * i);   //so the buttons don't overlap.
        btns.Name = "Button" + i;
        btns.Text = btns.Name;
        btns.Click +=new EventHandler(btns_Click);   //so we know when a button is clicked.
        this.Controls.Add(btns);   //add them to the form.
    }
}

public void btns_Click(object sender, EventArgs e)
{
    Button myBtn = (Button)sender;   //the clicked button is sent across as 'sender' so cast this as a Button
    MessageBox.Show("You Clicked" + myBtn.Name);    //and you can use the object as you wish!
}

BAM! Simple as that, we’ve created an array of buttons and assigned them an on_click event handler. There is a Tag property that can be set on the Button control and can also be used to identify which button was clicked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s