如何在C#中使用循环重命名多个按钮

3
我有一个类似战舰游戏的程序,其中有一个10x10个按钮的网格。在程序开始时,我想将所有按钮的文本更改为“---”,以显示该坐标没有被攻击。我无法找到一种方法来在一次循环中重命名所有按钮。这些按钮的名称为b00、b01、b02...它们代表它们的坐标。第一个数字是行号,第二个数字是列号。(例如,b69表示第7行第10列)。
希望你能帮忙!
提前致谢!
卢克
6个回答

5
您也可以使用扩展方法OfType()来根据指定类型进行筛选。请参见下一个示例。
foreach (Button btn in this.Controls.OfType<Button>())
   {

   btn.Text="New Name";
   }

通过使用OfType扩展方法,您可以看到无需将控件强制转换为Button类型。

希望这有所帮助。

祝好。


1
这样怎么样:
    foreach (Control c in this.Controls) {
        if (c is Button) {
            ((Button)c).Text = "---";
        }
    }

这段代码循环遍历表单上的所有控件(this),检查每个控件是否为按钮,并将其文本属性设置为“---”。或者,如果您的按钮位于其他容器中,例如面板,则应将 this.Controls 替换为 yourPanel.Controls

1
你可以从父容器中获取控件列表并循环遍历它们。
类似这样的代码:
foreach (Control c in myForm.Controls)
{
  if (c is Button)
  {
    ((Button)c).Text = "---";
  }
}

1

考虑将每个按钮添加到列表中:

// instantiate a list (at the form class level)
List<Button> buttonList = new List<Button>();

// add each button to the list (put this in form load method)
buttonList.add(b00);  
buttonList.add(b01);
... etc ...

然后你可以像这样设置给定的按钮:

buttonList(0).Text = "---"  // sets b00

或者将所有按钮都这样:

foreach (Button b in buttonList) {
   b.Text = "---";
   }

还有其他的可能性:

  • 将按钮放在2D数组中,以允许按行和列进行寻址。您仍然可以对数组进行foreach操作以一次性设置所有内容。

  • 通过编程方式创建按钮(并设置大小和位置),以避免在设计器中创建所有按钮。这也将允许您在运行时设置网格大小。


0
在这种情况下,我通常会将我经常要操作的控件存储到一个List或者更好的IEnumerable<>集合中,我通常会在构造函数或包含控件的Load事件处理程序(例如,如果这些控件包含在一个Form中,或者被包含在一个GroupBox中)中初始化这些集合。通过这样做,我希望减少每次需要这个集合时查找这些控件的开销。如果您只需要执行一次此操作,则不必添加buttons集合。
因此,代码可能如下所示:
// the collection of objects that I need to operate on, 
// in your case, the buttons
// only needed if you need to use the list more than once in your program
private readonly IEnumerable<Button> buttons;

在构造函数或加载事件处理程序中:
this.buttons = this.Controls.OfType<Button>();

然后,每当我需要更新这些控件时,我只需使用此集合:

foreach (var button in this.buttons)
{
    button.Text = @"---";

    // may wanna check the name of the button matches the pattern
    // you expect, if the collection contains other 
    // buttons you don't wanna change
}

0
foreach(Control c in this.Controls)
{
if(c.type==new Button().type)
{
Button b=(Button)c;
b.Text="";
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接