我有一个类似战舰游戏的程序,其中有一个10x10个按钮的网格。在程序开始时,我想将所有按钮的文本更改为“---”,以显示该坐标没有被攻击。我无法找到一种方法来在一次循环中重命名所有按钮。这些按钮的名称为b00、b01、b02...它们代表它们的坐标。第一个数字是行号,第二个数字是列号。(例如,b69表示第7行第10列)。
希望你能帮忙!
提前致谢!
卢克
希望你能帮忙!
提前致谢!
卢克
foreach (Button btn in this.Controls.OfType<Button>())
{
btn.Text="New Name";
}
通过使用OfType扩展方法,您可以看到无需将控件强制转换为Button类型。
希望这有所帮助。
祝好。
foreach (Control c in this.Controls) {
if (c is Button) {
((Button)c).Text = "---";
}
}
this
),检查每个控件是否为按钮,并将其文本属性设置为“---”。或者,如果您的按钮位于其他容器中,例如面板,则应将 this.Controls
替换为 yourPanel.Controls
。foreach (Control c in myForm.Controls)
{
if (c is Button)
{
((Button)c).Text = "---";
}
}
考虑将每个按钮添加到列表中:
// 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操作以一次性设置所有内容。
通过编程方式创建按钮(并设置大小和位置),以避免在设计器中创建所有按钮。这也将允许您在运行时设置网格大小。
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
}
foreach(Control c in this.Controls)
{
if(c.type==new Button().type)
{
Button b=(Button)c;
b.Text="";
}
}