I want to create 10 buttons on my form when I click on button1. No error with this code below but it doesnt work either.
private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < buttons.Capacity; i++)
{
this.Controls.Add(buttons[i]);
}
}
It doesn't work because the list is empty. Try this:
You can't add a Button to an empty list without creating a new instance of that Button. You are missing the
in your code plus get rid of the
.Capacity
use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3
You could do something like this:
If you want them to layout in any sort of reasonable fashion it would be better to add them to one of the layout panels (i.e. FlowLayoutPanel) or to align them yourself.
I came with the same doubt, with the current contribution on the issue I could came up with:
The expected behaviour is that, this will generate buttons using the current state of your window size, Always breaking a line when the next button would exceed the right margin of your window.
First, you aren't actually creating 10 buttons. Second, you need to set the location of each button, or they will appear on top of each other. This will do the trick: