1

We are supposed to code Conway's Game Of Life in a C# Winform application. So, I created a 10 by 10 "game board" out of buttons. Pink means dead, blue means alive. And for ease of access, each button is named after its coordinates on the game board (e.g. x1y1, x10y9, x5y5). But then I realized I have no idea how to loop through 100 form controls and perform do stuff to each individual according to their color/value. In HTML/Javascript, I used the following loop:

for(row = 1; row <= 10; row++){
    board[row] = new Array(10); //creates a 10 by 10 matrix to store the board's values in it.
    for(col = 1; col <= 10; col++){
        var position = "x" + row + "y" + col;
        var val = parseInt(document.board.elements[position].value);
        board[row][col] = val;

    }
}

So the question is this: Is there a way to call form controls through strings not variable names? Something like Form1.getControlByName(string) or something?

CubeMage
  • 61
  • 9
  • 1
    Use a class to hold your cells propeties (the grid position, for example). Then you can have a collection of classes that allows you to single out a specific cell in O1, without searching. Much handier when it comes to grouping. Or sorting. Or anything else. – Jimi Mar 30 '19 at 13:33

1 Answers1

1

You could set the Name property of each Button control you create. E.g. let that button is a reference to a Button control:

button.Name = "11";

Then you could use Control.ControlCollection.Find method to find the button control you are looking for as below:

Button button = this.Controls.Find("11", true).FirstOrDefault() as Button;

The this is a reference to the Form instance. You need to call FirstOrDefault, since Find returns an array of the Controls, whose name is "11". Last you have to use the as operator to convert the Control object to a Button. If conversion fails the value of button is null. So after this conversion you have to check if it is not null:

if(button != null)
{
    // place here your code
}
Christos
  • 53,228
  • 8
  • 76
  • 108