user2475740
user2475740

Reputation:

asp.net c# Label name increse

I'm just tried the change label name with a "foreach" loop but Visual Studio returned error to me.

I just tried to use the label in a "foreach" loop and wanted to make my work easier. The code is just like that.

 int i = 0;

        foreach (string a in dr)
        {
            Label6.Text = dr.GetString(i).ToString();
            i++;
        }

I don't understand why i can't use like this.

Label[i], Label(i) or label{i}

Can anyone know how can i use like this? Thanks for support :)

Upvotes: 0

Views: 479

Answers (1)

Andrei
Andrei

Reputation: 56716

Labels on your page do not compound an array. If you have say 6 Labels - this just 6 labels with 6 different IDs. That does not prevent you from naming them FirstLabel, SecondLabel, etc - and suddenly they cannot be accessed like an array.

However if you really named them Label1 through Label6 and what to leverage that fact - you can try using FindControl method:

int i = 6;
Label label = FindControl("Label" + i) as Label;

Note that FindControl is not recursive - you have to call it on the label's closest container, which is not always the page itself.

Upvotes: 1

Related Questions