Reputation: 23
I have about 20 checkboxes on the form. How can I name them to use them later in a for loop for example? A thing such an array checkBox[i]
.
Regards
Upvotes: 2
Views: 61
Reputation: 27633
CheckBox[] MyCheckBoxes = new CheckBox[20];
for (int i = 0; i < 20; i++)
{
MyCheckBoxes[i] = new CheckBox();
MyCheckBoxes[i].Checked = true;
//etc
}
Upvotes: 0
Reputation: 437336
I am assuming that the controls are being created as part of InitializeComponent()
, i.e. it's done by designer code.
The straightforward approach would be to do this after InitializeComponent
is called:
var checkboxes = new[]
{
checkBox1, // these are the names you have given
checkBox2, // to the checkboxes in the designer
checkBox3,
};
A better way would be to use LINQ to put all checkboxes in an array:
var checkboxes = this.Controls.OfType<CheckBox>().ToArray();
However, this will not work recursively and you may have to filter some checkboxes out of the collection if you don't want all of them to be in the array.
Upvotes: 1
Reputation: 1935
Check out container controls, they automatically create collections of the controls you place within them in design view.
Upvotes: 0
Reputation: 151588
Info here: http://msdn.microsoft.com/en-us/library/aa289500(v=vs.71).aspx
Upvotes: 0