3

I have a simple for loop as follows:

for (int i = 0; i > 20; i++)
{

}

Now I have 20 labels (label1, label2, label3 and so on..)

I would like to do something like:

for (int i = 0; i > 20; i++)
{
    label[i].Text = String.Empty;
}

What is the easiest way to accomplish this?

8
  • 6
    put the labels in an array, then use the code you posted? Commented Aug 27, 2012 at 13:09
  • The best would be to use descriptive names instead of Label123. Commented Aug 27, 2012 at 13:10
  • 2
    label1 is not the same as label[1]. Commented Aug 27, 2012 at 13:10
  • 1
    what is it? winforms? wpf? webforms? Commented Aug 27, 2012 at 13:11
  • 8
    your loop is wrong. use for (int i = 0; i < 20; i++) Commented Aug 27, 2012 at 13:12

5 Answers 5

14

If your labels are placed on one container, say Form, you may do the following:

foreach(Label l in this.Controls.OfType<Label>())
{
    l.Text = string.Empty;
}

Same for any other container, say, Panel or GroupBox, just replace this with the name of the container (panel1.Controls, etc.)

Sign up to request clarification or add additional context in comments.

Comments

2

I'd call your solution a design-flaw, but I'd go for something like this:

var itemArray = this.Controls.OfType<Label>();

foreach(var item in itemArray)
{
    item.Text = string.Empty;
}

Comments

2

Create an array or list of labels and loop through that list to set the properties of each label

List<Label> labels = new List<Label>();
labels.Add(label1);

foreach(Label l in labels)
{
    l.Text = String.Empty;
}

Comments

1

Don't know if its the easiest, it is the shortest though..

this.Controls.OfType<Label>().ToList().ForEach(lbl => { lbl.Text = String.Empty; });

1 Comment

I gave your answer only an upvote for using ForEach...still getting accustomed to it myself
0

Maybe you can use FindControl with something like

for(int i = 0; i < 5; i++)
{
   (FindControl("txt" + i.ToString())).Text = String.Emty;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.