【问题标题】:changing properties of multiple buttons at once using for loop in visual c# [duplicate]在visual c#中使用for循环一次更改多个按钮的属性[重复]
【发布时间】:2014-08-03 09:02:43
【问题描述】:

在 Visual c# 中,我构建了一个包含 10 个按钮的 win 表单 我有以下button10_Click(object sender, EventArgs e) 的代码:

button1.Text = "A".toString();
button2.Text = "B".toString();
button3.Text = "C".toString();
...
button9.Text = "I".toString();

但是代码太长了。有什么办法可以在循环中做到这一点? 像这样的:

char x = 'A';
for(int i = 1; i<10;i++,x++)
{
    button[i].Text = x.toString();
}

请帮忙

【问题讨论】:

  • “A”已经是string。无需添加ToString。 ;-)

标签: c# winforms button


【解决方案1】:

您可以将您的 Button 控件添加到列表并迭代该列表。

int charIndex = 65;
foreach (Button b in buttonList)
{
   b.Text = new String((char)charIndex, 1);
   charIndex++;
}

如果你没有嵌套控件并且你想将所有按钮放到一个列表中,你可以这样做

List<Button> buttonList= Controls.OfType<Button>().ToList();

然后像上面那样迭代。

【讨论】:

  • 另一件可能更具可读性的事情是使用 char[] characters = "ABCDEFGHILM".ToCharArray() 并访问数组以获取正确的字符。
  • @FabioMarcolini - 这是个好主意。
猜你喜欢
  • 2022-06-17
  • 1970-01-01
  • 2018-05-30
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多