Reputation: 65
I am trying to call a label dynamically but have no idea how to do it.
I want to make a label visible depending on the integer.
So if int i = 1
, then label1
should turn visible and if i = 2
, then label2
should turn visible, and so on and so forth.
How do I do this?
int i = word.indexOf("t");
//This is where I need the label to be dynamically called
I tried ("label" + i.ToString()).Visible = true;"
in a lazy attempt.
Upvotes: 1
Views: 839
Reputation: 31
Label1.Visible = (i == 1); // if i is not 1, then label1 is not visible
Upvotes: 0
Reputation: 40586
Here's a dynamic solution:
foreach (var label in Controls.OfType<Label>())
label.Visible = (label.Name == "label" + i);
Note that:
this will hide all labels that are not named "label" + i
. You may need additional filtering logic if there are any other labels on the form/container
the above code works if the labels are direct descendants of the form. If that's not the case (for example, the labels are children of a panel called panel1
), then you'll need to replace Controls
with panel1.Controls
Upvotes: 3