![](/img/trans.png)
[英]How can I change multiple .text values to “”, through calling a method?
[英]How can I change myLable1.Text by calling it as a variable
首先,我说我只是在学习C#,这是我的序言。 除了基本的JavaScript之外,我没有其他编程经验,因此我仍然不确定很多正确的术语。 关于这个问题...
假设我有10个标签; myLabel1,myLabel2,myLabel3等,我有一个名为i的变量。
那么,如何通过切换变量i的结束号来更改myLabel的.Text? 我尝试制作一个新的字符串:
string labelNumber = "myLable" + Convert.ToString(i);
接着:
lableNumber.Text = "some text";
显然,这是行不通的,因为.text不是lableNumber的已知方法。
与大多数其他编译语言一样,C#不能像许多脚本语言一样让您轻松地做到这一点。
如果要通过字符串访问控件,则需要将它们收集在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
现在,您可以按名称访问每个字符串:
labels["myLabel3"].Text = "hi there";
请注意,将它们添加到Dictionary
中(或者,如果您愿意通过索引访问它们,则添加到List<T>
),在循环创建它们时需要这样做,因为以后将无法访问它们。 至少不是没有反思 ,这对于这种情况来说太过猛了。
还请注意 ,变量名不是字符串,而是编译器的标记,而变量名是 Name
属性 ,后者是字符串,但并不意味着要标识变量,因为它不必唯一 ,可以随时更改 。
我认为您正在尝试执行以下操作:
// 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.