Tony
Tony

Reputation: 1185

How to use different labels in one for cycle

ex: label[i].text. in

int r = GridView1.Rows.Count;
for (int i = 0; i < r; i++) 
{
    Label[i]+"1".text="something";   
}

Here, in one for cycle, I want to fill different labels. Label id's are Label01, Label02,Label03 and so on. What is the correct syntax?

Upvotes: 0

Views: 222

Answers (3)

denza
denza

Reputation: 1298

Label myLabel = this.FindControl("Label"+i+"1") as Label; 
myLabel.Text = "my text"; 

THIS should solve your problem

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273784

If you can 'predict' the Id of the Label then you can find it:

int r = GridView1.Rows.Count;
for (int i = 0; i < r; i++) 
{
     string id = "baseName" + i;  // your naming scheme
     var lbl = (Label) this.FindControl(id);
     lbl.text="something";   
}

Upvotes: 3

Oded
Oded

Reputation: 499362

You can add all the labels into a List<Label> or SortedList<Label> and iterate over that.

var labels = new SortedList<Label>();
lables.Add("Lable01", Label01);
lables.Add("Lable02", Label02);
...

int r = GridView1.Rows.Count;
for (int i = 0; i < r; i++) 
{
     lables["Label" + i.ToString("00")].text = "somthing";
}

There are no control arrays in .NET, as there were in VB6.

Upvotes: 1

Related Questions