[英]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. 首先,我说我只是在学习C#,这是我的序言。 I have no prior programming experience other than basic JavaScript so I'm still unsure on a lot the correct terminology.
除了基本的JavaScript之外,我没有其他编程经验,因此我仍然不确定很多正确的术语。 On to the question...
关于这个问题...
Let's say I have 10 labels; 假设我有10个标签; myLabel1, myLabel2, myLabel3 etc and I have a variable called i.
myLabel1,myLabel2,myLabel3等,我有一个名为i的变量。
So how can I change the .Text of myLabel by switching out the end number for the variable i? 那么,如何通过切换变量i的结束号来更改myLabel的.Text? 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. 显然,这是行不通的,因为.text不是lableNumber的已知方法。
C# as most other compiled languages will not let you do that as easily as many scripting languages. 与大多数其他编译语言一样,C#不能像许多脚本语言一样让您轻松地做到这一点。
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>
: 如果要通过字符串访问控件,则需要将它们收集在
Dictionay<string, Control>
或者,如果仅关心Labels
,则需要将其收集在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; 请注意,将它们添加到
Dictionary
中(或者,如果您愿意通过索引访问它们,则添加到List<T>
),在循环创建它们时需要这样做,因为以后将无法访问它们。 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.. 还请注意 ,变量名不是字符串,而是编译器的标记,而变量名是
Name
属性 ,后者是字符串,但并不意味着要标识变量,因为它不必唯一 ,可以随时更改 。
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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.