在循环中动态更改 C# 变量名称
我正在尝试在 C# 中的 MySQLDataReader 中启用并重命名标签。如果可能的话,我愿意在循环之外执行此操作,但想知道是否有一种方法可以动态更改变量的名称。例如:
while (listNamesREAD.Read())
{
int i = 0;
//TextBox1.Text = TextBox1.Text + fieldnames.GetString(0) + ", ";
stringArray[i] = "List #" + listNamesREAD.GetString(0) + ": " + listNamesREAD.GetString(1);
list1Label.Text = stringArray[i];
i++;
}
如果可能的话,我希望代码能够在每次循环时更改 list1Label 的名称。我对 Visual C# 比较陌生,因此我们将不胜感激。
using (MySqlCommand cmd0 = new MySqlCommand(listNames, conn))
{
conn.Open();
listNamesREAD = cmd0.ExecuteReader();
try
{
while (listNamesREAD.Read())
{
int i = 0;
//TextBox1.Text = TextBox1.Text + fieldnames.GetString(0) + ", ";
stringArray[i] = "List #" + listNamesREAD.GetString(0) + ": " + listNamesREAD.GetString(1);
list+i+Label.Text = stringArray[i];
i++;
}
}
如果可能的话,我也愿意在 DataReader 之外完成此任务。使用普通的 while 循环,因为数组大小是动态的,所以我确切地知道要循环多少次——这只是动态更改变量名称的问题。
I am trying to enable and rename labels within a MySQLDataReader in C#. I am willing to do this outside of the loop if possible, but was wondering if there was a way to dynamically change the name of a variable. For example:
while (listNamesREAD.Read())
{
int i = 0;
//TextBox1.Text = TextBox1.Text + fieldnames.GetString(0) + ", ";
stringArray[i] = "List #" + listNamesREAD.GetString(0) + ": " + listNamesREAD.GetString(1);
list1Label.Text = stringArray[i];
i++;
}
If possible I would like the code to be able to change the name of list1Label each time it loops through. I am relatively new to Visual C# so any help would be greatly appreciated.
using (MySqlCommand cmd0 = new MySqlCommand(listNames, conn))
{
conn.Open();
listNamesREAD = cmd0.ExecuteReader();
try
{
while (listNamesREAD.Read())
{
int i = 0;
//TextBox1.Text = TextBox1.Text + fieldnames.GetString(0) + ", ";
stringArray[i] = "List #" + listNamesREAD.GetString(0) + ": " + listNamesREAD.GetString(1);
list+i+Label.Text = stringArray[i];
i++;
}
}
I am also willing to accomplish this outside of the DataReader if possible as well. Using a normal while loop because the array size is dynamic so I know exactly how many times to loop through -- it's just a matter of dynamically changing variable names.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要循环遍历一个
TextBox
数组。由于 C# 是一种静态类型语言,因此无法按照您想要的方式完成此操作。您可以使用
Controls
属性(它是表单中所有控件的集合)来完成您的需要。您可以通过索引器和控件名称访问控件:You will need to have an array of
TextBox
es you loop through. There is no way to accomplish this how you want to as C# is a statically typed language.You can use the
Controls
property (which is a collection of all controls in the form) to accomplish what you need. You can access the controls by the indexer and the Controls' name:您想更改标签名称以实现哪个目标吗?
您是否有名为:label1、label2、label3 的标签并且您想更改它们的文本属性?
你可以使用 linq 来做到这一点。
do you want to change label name to accomplish which aim?
do you have label named as: label1, label2, label3 and you'd like to change their text property?
you could do that by using linq.