简体   繁体   中英

How can I change myLable1.Text by calling it as a variable

Let me preface this by saying I have only been learning c# a few days. I have no prior programming experience other than basic JavaScript so I'm still unsure on a lot the correct terminology. On to the question...

Let's say I have 10 labels; myLabel1, myLabel2, myLabel3 etc and I have a variable called i.

So how can I change the .Text of myLabel by switching out the end number for the variable i? I tried making a new string:

string labelNumber = "myLable" + Convert.ToString(i);

and then:

lableNumber.Text = "some text";

Clearly this doesn't work because .Text is not a known method on lableNumber.

C# as most other compiled languages will not let you do that as easily as many scripting languages.

If you want to access your controls by a string you need to collect them in a Dictionay<string, Control> or, if you only care about Labels , a Dictionay<string, Label> :

Dictionary<string, Label> labels = new Dictionary<string, Label>();

// you can do this in a loop over i:
Label newLabel = new Label();
newLabel.Name = "myLabel" + Convert.ToString(i);

// maybe set more properties..
labels.Add(newLabel.Name, newLabel );     // <-- here you need the real Label, though!
flowLayoutPanel1.Controls.Add(newLabel )  // <-- or wherever you want to put them

Now you can access each by its name as string:

labels["myLabel3"].Text = "hi there";

Note that to add them to the Dictionary , (or a List<T> if you are happy with accessing them by an index,) you need to do it when you create them in a loop as you can't access them later; at least not without reflection , which imo is overkill for the situation..

Also note the difference between the variable name which not a string but a token for the compiler and its Name property , which is a string but not meant to identify the variable as it need not be unique and can be changed at any time..

I think you are trying to do something like this:

// Create N label xontrols
Labels[] labels = new Labels[n];

for (int i = 0; i < n; i++)
{
    labels[i] = new Label();
    // Here you can modify the value of the label which is at labels[i]
}

// ...

labels[2] .Text = "some text";

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