I have several labels on a form that I would like to be able to reset to “0”.
I have it worked out by referencing each label. I have also used an array and for loop, this seems a little more efficient. Is there a way to reference each label name by using the for variable and constructing a string the evaluates to the label name without an array?
Like this:
for (int x = 0; x < 6; x++)
lbls[x].Text = "0";
Here is my code:
// Clear form labels
private void btnClear_Click(object sender, EventArgs e)
{
Label[] lbls = new Label[]
{
lbl1, lbl2,lbl3,lbl4,lbl5,lbl6
};
for (int x = 0; x < 6; x++)
lbls[x].Text = "0";
//lbl1.Text = "0";
//lbl2.Text = "0";
//lbl3.Text = "0";
//lbl4.Text = "0";
//lbl5.Text = "0";
//lbl6.Text = "0";
}
If you don’t have other labels:
will give you an
IEnumerableof all the labels on your form, and then you can use Simons code: