开发者

using variables in object names

开发者 https://www.devze.com 2023-03-03 20:50 出处:网络
Okay so lets say I have a integer called abc and I set abc to 2. How do I say label2.visible = true;?

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 = tru开发者_JAVA技巧e;


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.


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.


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;


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

精彩评论

暂无评论...
验证码 换一张
取 消