Aasas
Aasas

Reputation: 51

How to access labels from loop and change their text

I have list where are 6 sentences which I want to put in 6 different labels. All six labels are named Slot0Sentence, Slot1Sentence, Slot2Sentence...

This is how I loop

for (int i = 0; i < ls.Count; i++) 
{
    Slot0Sentence.Text = ls[i];
}

However I dont know how to access other labels. If there would be normal string I would do Slot + i + Sentence but in this case this dont work.

Upvotes: 0

Views: 523

Answers (2)

Masoud Mohammadi
Masoud Mohammadi

Reputation: 1739

with an array of labels you can control their properties. you don't need design here, you can do that with code.

Label[] l = new Label[6];
int x = 20;
for (int i = 0; i < l.Length; i++)
{
    l[i] = new Label();
    l[i].Name = "Hello " + i.ToString();
    l[i].Text = "Hello " + i.ToString();
    l[i].Location = new Point(x, 10);
    x += 100;
}

you can change the names and text to whatever you like.

Upvotes: 1

Filip
Filip

Reputation: 1864

I'd just use Children property of parent container (Grid, StackPanel,..). This gives you a collection which supports indexes. Additionally, in case you have different controls, use if statement

if(element in Label)
{
 element.Text = ...
}

Upvotes: 0

Related Questions