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]
.
Rega开发者_C百科rds
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.
Info here: http://msdn.microsoft.com/en-us/library/aa289500(v=vs.71).aspx
Check out container controls, they automatically create collections of the controls you place within them in design view.
CheckBox[] MyCheckBoxes = new CheckBox[20];
for (int i = 0; i < 20; i++)
{
MyCheckBoxes[i] = new CheckBox();
MyCheckBoxes[i].Checked = true;
//etc
}
精彩评论