user1189242
user1189242

Reputation:

use more than one labels

In my ASP.NET application I have around 7 to 8 Label controls and currently my code to set their Text value looks like this:

while (MyReader.Read())
{
    if(j>=i && j-i<=10 && j<(10+i+a))
    {
        Label"+[j]+".Text=a;
    }
    j++;
}

Now my label name statred from 1 to 8, I dont want to repaeat my statements like:

What to do?

Upvotes: 0

Views: 111

Answers (3)

the_joric
the_joric

Reputation: 12241

That actually should resolve your issue:

((Label)Page.FindControl("Label" + j)).Text = a;

However as Jon suggested, it would be better to manage your labels in more generic way using list or something.

Upvotes: 1

Mujassir Nasir
Mujassir Nasir

Reputation: 1730

try this

while (MyReader.Read())
{
    if(j>=i && j-i<=10 && j<(10+i+a))
    {
        Label lbl = new Label();
        lbl.Name="Label" + j;
        lbl.Text = a;
    }
    j++;
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502316

Rather than having seven different variables (label1, label2 etc) have one variable of type List<Label> or something similar. Then you can access them by index, iterate over all of them etc.

If you're relying on the designer to declare your variables for you, you could leave them alone but also have a collection variable which you populate in one place. The only problem is that then if you reassign the individual variables, that change won't be reflected in your collection.

As an aside, it looks like you've got your presentation logic and your data access logic in one place - you should consider separating them...

Upvotes: 3

Related Questions