Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename multiple buttons in one loop in C#

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

like image 805
Luke Hottinger Avatar asked Dec 20 '25 06:12

Luke Hottinger


2 Answers

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

like image 141
alnaji Avatar answered Dec 22 '25 19:12

alnaji


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.

like image 34
Jay Riggs Avatar answered Dec 22 '25 19:12

Jay Riggs