C # button click event. Extract coordinates from a two-dimensional array

I am making a minesweeper game in C #, and this part of my code checks to see if the user has pressed a specific button on the grid. However, the way to do this I believe that he broke the xy coordinates of the button that he pressed.

The value of the way the code works is that there are two two-dimensional arrays. There are 100 buttons on the button [10,10]. and behind the grid, the grid is called [10,10], and on the grid I said that -1 is a bomb, and 1 is empty space. I am trying to extract the xy coordinate, which he clicks on a button and checks the grid. And this is the code below:

However, when I click the button - in the code int x = System.Convert.ToInt32 (split [0]); I get a "Fix System.FormatException".

What am I doing wrong?

void bttnOnclick(object sender, System.EventArgs e)
    {

        Button bttnClick = sender as Button;

        string[] split = bttnClick.Name.Split(new Char[] { ' ' });

        int x = System.Convert.ToInt32(split[0]);
        int y = System.Convert.ToInt32(split[1]);


        if (grid[x, y] == -1)
        {
            //Game Over!
            for (int xx = 0; xx < SizeX; xx++)
            {
                for (int yy = 0; yy < SizeY; yy++)
                {
                    if (grid[xx, yy] == -1)
                    {
                        buttons[xx, yy].Visible = false;
                    }

                }
            }
        }
    }
+4
4

, , name.

Button[,] buttons = new Button[10, 10];

for (int i = 0; i < buttons.GetLength(0); i++ )
{
     for(int j = 0; j < buttons.GetLength(1); j++)
     {
          buttons[i, j] = new Button()
          {
               Name = i + " " + j
          };
     }
}
+1

, , split[0] - , .

:

  • .

  • Point Tag button.Tag= new Point(x,y); point p= (Point)(((Button)sender).Tag); p.X, p.y .

  • TableLayoutPanel GetColumn GetRow

    TableLayoutPanel . , GetColumn GetRow TableLayoutPanel :

    var column = tableLayoutPanel1.GetColumn((button)sender);
    var row = tableLayoutPanel1.GetRow((button)sender);

+2

:

'System.FormatException'

- int x = System.Convert.ToInt32(split[0]); int. , , . string splitString = System.Convert.ToInt32(split[0]);. . , splitString. , , .

+1
string[] split = bttnClick.Name.Split(new Char[] { ' ' });

First, I would like to indicate that the Name property for the control has some limitations. I do not understand how your code compiles. Take a look at this WPF Name property .
You can use the tag property and / or use the underscore (_) instead of space.

As for your question: the contents of the [] split line have the different content that you expect. Take a look at it with a debugger.

0
source

Source: https://habr.com/ru/post/1619529/


All Articles