Often you want to address several controls at once, for example, all labels that have the names of Label0 – Label 19.
This can be done by accessing the this.Controls collection in a loop.
Here’s an example:
1 2 3 4 5 6 7 | for (int i = 0; i < 20; i++) { Label l = (Label)this.Controls["label" + i.ToString()]; l.BackColor = Color.Red; } |
This works as long as all controls are in one container. If you are in different containers (panel, splitconteiner, etc.), you have to specify this control list. eg this.Panel1.Controls
Or you can use another an example is via foreach statement, when you click the program’s Button button, the following code executes.
1 2 3 4 5 6 7 8 | private void btnButton_Click(object sender, EventArgs e) { lstControls.Items.Clear(); foreach (Button btn in Controls.OfType<Button>()) lstControls.Items.Add(btn.Name); } |