简体   繁体   中英

using variables in object names

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;

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;
}

You want to use the Control.FindControl method.

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

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

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.

一种方法是拥有和标签数组,然后根据数量你可以做:

label_array[abc].visible = true;

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.

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.

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;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM