0

I am working on winform application in asp.net using c#. I have 10 labels on my winform created in the designer mode, called Label0 to Label9. Now I want to change the Text property of all the labels at once as per the data I acquire in the middle of execution of my program. i want to do something like this :

for (int i = 0; i < 10; i++)
{
Label[i].Text = "Hello, this is label: "+ i.ToString();
}

Now, of course this won't work. But how can this be done? how can i call the label like its done in an array? If not possible, then what can be the best alternative solution for my problem?

2
  • "winform application in asp.net"? You should rephrase that. Commented May 26, 2015 at 10:16
  • I don't understand winforms in asp.net... Anyway, create an array of type Label and add your labels to it, then in your loop access the correct label by specifying the index? Commented May 26, 2015 at 10:18

2 Answers 2

3

If you are talking about WinForms, then you can do like this:

private void Form1_Load(object sender, EventArgs e)
{
    // Form1_Load is just sample place for code executing
    for (int i = 1; i < 10; i++)
    {
        var label = Find<Label>(this, "label" + i);
        label.Text = "Hello, this is label: " + i.ToString();
    }

}

private T Find<T>(Control container, string name)
    where T : Control
{
    foreach (Control control in container.Controls)
    {
        if (control is T && control.Name == name)
            return (T)control;
    }

    return null;
}

This code will search label in form controls, and then return it based on control name and type T. But it will use just parent form. So if your label is in some panel, then you need to specify panel as container parameter. Otherwise Find method can be updated as recursive method, so it will search inside all form subcontrols, but if there will be two Label1 controls, then it will return just first one, that might be not correct.

Sign up to request clarification or add additional context in comments.

Comments

0

If you can put all Label on a panel after the you can use below code to change the text

          foreach (Control p in panal.Controls)
            if (p.GetType == Label)
               p.Text = "your text";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.