I have a battleship-like program where there is a 10 x 10 grid of buttons. In the beginning of the program, i would like all of the buttons' text to be changed to "---", which shows that no one has shot at that coordinate. I can't seem to find a way to rename all of the buttons in one loop. The buttons all have names b00, b01, b02... which show their coordinates. the first number is the row and the second number is the column. (i.e. b69 represents row 7, column 10).
Hope you can help!
Thank you in advance!
Luke
You can also use Extension Method OfType() to filtering based on specified type.See the next example
foreach (Button btn in this.Controls.OfType<Button>())
{
btn.Text="New Name";
}
as you can see by using OfType extension method you do not need to casting the control to Button Type
Hope that help.
Regards
How about this:
foreach (Control c in this.Controls) {
if (c is Button) {
((Button)c).Text = "---";
}
}
This snippet loops through all controls on the form (this), check if each is a Button and if you set its Text property to "---". Alternately, if your buttons were on some other container, such as a Panel you'd replace this.Controls with yourPanel.Controls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With