如何在C#中重命名一个循环中的多个按钮

我有一个类似战舰的程序,其中有一个10 x 10网格的按钮。 在程序的开头,我希望所有按钮的文本都改为“—”,这表明没有人在那个坐标上射击。 我似乎无法找到一种方法来重命名一个循环中的所有按钮。 按钮都有名称b00,b01,b02 ……显示其坐标。 第一个数字是行,第二个数字是列。 (即b69代表第7行,第10列)。

希望你能帮忙!

先感谢您!

卢克

您还可以使用Extension Method OfType()根据指定的类型进行过滤。请参阅下一个示例

foreach (Button btn in this.Controls.OfType 

正如您可以通过使用OfType扩展方法看到的那样,您不需要将控件转换为Button Type

希望有所帮助。

问候

这个怎么样:

  foreach (Control c in this.Controls) { if (c is Button) { ((Button)c).Text = "---"; } } 

此代码段循环遍历表单上的所有控件( this ),检查每个控件是否为Button,以及是否将其Text属性设置为“—”。 或者,如果您的按钮位于某个其他容器(例如Panel)上,则可以使用yourPanel.Controls替换this.Controls

您可以从父容器中获取控件列表并循环遍历它们。

像这样的东西:

 foreach (Control c in myForm.Controls) { if (c is Button) { ((Button)c).Text = "---"; } } 

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

 // instantiate a list (at the form class level) List 

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

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

或者所有按钮:

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

其他可能性比比皆是:

  • 将按钮放在2D数组中以允许按行和列进行寻址。 您仍然可以对arrays进行预测以立即设置所有内容。

  • 以progamatically方式创建按钮(以及设置大小和位置),以避免必须在设计器中创建所有按钮。 这还允许您在运行时设置网格大小。

我在这种情况下所做的是将我想要经常操作的控件存储到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 

在构造函数或load事件处理程序中:

 this.buttons = this.Controls.OfType 

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

 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 } 
 foreach(Control c in this.Controls) { if(c.type==new Button().type) { Button b=(Button)c; b.Text=""; } }