-1

Using C# and Windows Forms, i would like to use the name of a Label as a parameter of another function, like this:

 startBox(label_box, "11", Color.Red);

Definition of startBox:

  private void startBox(Label label, string text, Color color) {
        label.BackColor = color;
        label.Visible = true;
        label.Enabled = true;
        label.Text = text;
    }

But, is there any way to convert an string to the name of a Label? In my case, label_box is a string.

ps¹. I need to do this because i have N Labels and the name is should be typed by the user.

ps². To Invoke a method using a string i used the MethodInfo.

EDIT: The solution using Controls does not apply. In my case, a string is given as an input, if the string is the name of one of the labels the function is called.

Thank you, and sorry for the spelling flaws in English.

Tuxpilgrim
  • 381
  • 1
  • 12
  • 3
    winforms? wpf? what tech are you using? – Maximilian Burszley Sep 26 '18 at 20:00
  • windows forms, question edited :) – Tuxpilgrim Sep 26 '18 at 20:02
  • I think you want this: [How to: Access Controls by using the Controls Collection](https://msdn.microsoft.com/en-us/library/yt340bh4.aspx?f=255&MSPPError=-2147217396) – 001 Sep 26 '18 at 20:04
  • @JohnnyMopp i know the name of the `Labels` (Controls it's just to get all the controls). What I need is to get a string as an input and check for a label with that name, and call the function, thks :) – Tuxpilgrim Sep 26 '18 at 20:13
  • See the first answer in the dupe. Looks to me like exactly what you need: `Label label = this.Controls.Find(label_box, true).FirstOrDefault() as Label;` Or more simply: `Label label = this.Controls[label_box] as Label` (but you need to ensure is exists and is not nested). – 001 Sep 26 '18 at 20:32

1 Answers1

1

so you want to be able to operate on a label, where the name of the label is supplied as input. I would do this with a dictions

var lDict = new Dictionary<string, Label>();
lDict["l1"] = Label1;
lDict["l2"] = Label2;
....

then

void Func(string labelName)
{
  var label = lDict[labelName];
  label.Visible = true;
  ...
}

you could do all sorts of complicated reflection tings but that feels like overkill

pm100
  • 48,078
  • 23
  • 82
  • 145