FicVic
FicVic

Reputation: 95

Using variable in label name

Can something like this be done?

var test = 1;

label+test+.Text = "Some text goes here...";

Which would result in:

label1.Text = "Some text goes here...";

I wouldn't mind using switch-case if I had few cases, but I have like 40 labels that I would like dynamically assigned text depending on the variable value.

Upvotes: 2

Views: 11673

Answers (3)

Idle_Mind
Idle_Mind

Reputation: 39122

I have like 40 labels that I would like dynamically assigned text depending on the variable value

Here's another example, which is basically the same approach as Handoko's:

for(int i = 1; i <= 40; i++)
{
    Label lbl = this.Controls.Find("label" + i.ToString(), true).FirstOrDefault() as Label;
    if (lbl != null)
    {
        lbl.Text = "Hello Label #" + i.ToString();
    }
}

Upvotes: 2

user836846
user836846

Reputation: 74

var test = 1;
Control label = this.FindControl("label" + test);
if(label != null)
{
  label.Text = "Some text goes here...";
}

More informationon FindControl is available at, https://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol%28v=VS.100%29.aspx?f=255&MSPPError=-2147217396

Upvotes: 1

Han
Han

Reputation: 3072

Use Controls.Find() in your form.

void Button1Click(object sender, EventArgs e)
{
    var test = 1;
    var labels = Controls.Find("label" + test, true);
    if (labels.Length > 0)
    {
        var label = (Label) labels[0];
        label.Text = "Some text goes here...";
    }
}

Upvotes: 4

Related Questions