Using variables in object names

So, let's say that I have an integer abcand I set abc to 2.How to say label2.visible = true;?

I mean, if I set abc to 3, I want to do label3.visible = true;

+3
source share
7 answers

It seems to me that the easiest way to insert your controls into an array is as follows:

Label[] labels = new Label[] { label0, label1, label2, label3 };

Switch visibility as follows:

void SetVisibility(int index, bool visible)
{
    labels[index] = visible;
}
+6
source

You want to use the method Control.FindControl.

Label label = myForm.FindControl("label" + val) as Label;

if (label != null)
{
    // use...
}
+6
source

- :

var theLabel = (Label) this.Controls.Find("label" + abc.toString());
theLabel.Visible = true;

, .

+3

- , , :

label_array[abc].visible = true;
+2

To answer your real question, perhaps this is possible by reflection, but not what you really would like to do, I cannot come up with the right example of use.

As others have already written, use an array.

+2
source

C # Really does not support this type of syntax.

Put labels in some structure and use it to manage labels. Here are some 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 can get shortcuts from the list of parent forms of child controls and set the visibility this way.

+2
source

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;

    }
0
source

All Articles