none
Array Of Label Controls Or Similar Solution RRS feed

  • Question

  • I need to assign an undetermined number of labels to my program.

    label1.Text
    label2.Text
    label3.Text
    and so on


    I though I could use the following code

    setLabelText (label + "1", "test")


    private void setLabelText(Label lbl,string sToSet)
    {
         lbl.Text = sToSet;
    }

    but i cannot convert a string to a label.

    Does anyone know how i can easily do this without having to hard code 50 labels (which will grow and shrink depending on the user)

    Thursday, April 30, 2009 3:30 AM

Answers

  • Alternately you can access the Controls collection by name:

    for (int n = 1; n <= 3; n++)
        this.Controls["label" + n.ToString()].Text = "Test";

    This assumes that the labels are immediate children of the form. If they are contained in child containers, things get a little more complicated.
    • Proposed as answer by Navin Narayan Thursday, April 30, 2009 4:34 AM
    • Marked as answer by liurong luo Monday, May 4, 2009 6:55 AM
    Thursday, April 30, 2009 4:29 AM

All replies

  • How about using an array of label controls...

    Sample implementation is here
    Regards, Navin Narayan
    • Proposed as answer by liurong luo Monday, May 4, 2009 6:55 AM
    Thursday, April 30, 2009 3:45 AM
  • Alternately you can access the Controls collection by name:

    for (int n = 1; n <= 3; n++)
        this.Controls["label" + n.ToString()].Text = "Test";

    This assumes that the labels are immediate children of the form. If they are contained in child containers, things get a little more complicated.
    • Proposed as answer by Navin Narayan Thursday, April 30, 2009 4:34 AM
    • Marked as answer by liurong luo Monday, May 4, 2009 6:55 AM
    Thursday, April 30, 2009 4:29 AM