Reputation: 425
Okay so lets say I have a integer called abc
and I set abc to 2.
How do I say label2.visible = true;
?
I mean, if I set abc to 3 I want to make label3.visible = true;
Upvotes: 3
Views: 8273
Reputation: 18028
A way of doing it is to have and Array of Labels and then according to number you can do :
label_array[abc].visible = true;
Upvotes: 2
Reputation: 22332
You want to use the Control.FindControl
method.
Label label = myForm.FindControl("label" + val) as Label;
if (label != null)
{
// use...
}
Upvotes: 6
Reputation: 3218
You could do something like this:
var theLabel = (Label) this.Controls.Find("label" + abc.toString());
theLabel.Visible = true;
This code is untested and off the top of my head but it should work.
Upvotes: 3
Reputation: 11471
Two simple examples
if(abc == 2)
{
label2.visible = true;
label3.visible = false;
}
else if(abc ==3)
{
label3.visible = true;
label2.visiable = false;
}
or use a switch statement
switch(abc)
{
case 2:
label2.visible = true;
break;
case 3:
label3.visible = true;
break;
}
Upvotes: 0
Reputation: 6597
C# Really doesn't support that type of syntax.
Put the labels into some kind of structure and use it to manipulate the labels. Here a few examples:
List<Label> labels = new List<Label>();
int i = /* some valid index (0 based) */
labels[i].visible = true;
Dictionary<string, Label> labelDict = new Dictionary<string, Label>();
labelDict.add("label1", label1);
labelDict["label1"].visible = true;
Alternatively you could get the Labels from the parent form's list of child controls and set the visibility that way.
Upvotes: 2
Reputation: 28834
To answer your actual question, this is probably possible by reflection, but not something you would really want to do, i can't think of a valid use case.
As others have posted, use an array.
Upvotes: 2
Reputation: 81516
Seems to me its easiest to put your controls into an array as follows:
Label[] labels = new Label[] { label0, label1, label2, label3 };
Toggle the visibility like this:
void SetVisibility(int index, bool visible)
{
labels[index] = visible;
}
Upvotes: 6