D P.
D P.

Reputation: 1079

In C#, writing text in to lables

The name of the label that I want to write text in too can be changed depending on some condition. For example, I have 20 labels, but I may want to write my text in to the first 5 or 6 labels.

label1.Text = "1st result";
label2.Text = "2nd result";
label3.Text = "3rd result";

Instead of naming label2, label3, is there a way I can change the last digit of the label? For example, something like

label[i].Text = "2nd result";//i will hold the value 2

Upvotes: 1

Views: 72

Answers (3)

tariq
tariq

Reputation: 2258

Same using lists:

List<Label> labels = new List<Label>();
labels.AddRange(new Label[] { new Label(), new Label() });

Then access with index

labels[i].Text = "yourOne";

Upvotes: 0

TGH
TGH

Reputation: 39268

List<Label> labels = somePanel.Controls.OfType<Label>().ToList();
labels[i] = "whatever";

You can access the Labels via their parent container.

Upvotes: 4

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

Use array of Label:

Label[] labels = new Label[] { label1, label2, label3 };

Then you can do

labels[i].Text = "2nd result"; //i will hold the value 2

Upvotes: 2

Related Questions