Melih Ozturk
Melih Ozturk

Reputation: 3

Can't take an instance using Controls.Add

I'm triyng to create buttons programmatically. I don't want to use Button btn = new Button();.. btn.height=.... control.Add(btn);. The code I'm using can add the buttons to the form but I can't take an instance so I can't create button.click event. Can anybody help me to solve it. The code I'm using below thanks.

int k = 0;
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        Controls.Add( 
            new Button() 
            { 
                Top = 50 + (50 * i), 
                Left = 50 + (50 * j), 
                Width = 50, Height = 50, 
                Text = (++k).ToString()
            });
    }
}

Upvotes: 0

Views: 24

Answers (1)

Tor
Tor

Reputation: 631

If you don't want to create a button, and subscribe directly to the event (i don't know why is this important), you can do this:

private void Method()
{
    int k = 0;
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            Controls.Add(new Button() { Top = 50 + (50 * i), Left = 50 + (50 * j), Width = 50, Height = 50, Text = (++k).ToString() });
        }
    }
    Controls.OfType<Button>().ToList().ForEach(x => x.Click += Button_Click);
}

private void Button_Click(object sender, System.EventArgs e)
{
    MessageBox.Show((sender as Button).Text);
}

Upvotes: 1

Related Questions