-4

I have a 2d arrays button [5,5] all blue color...how to randomly generate 5 red button in the array...?

int Rows = 5;

int Cols = 5;

        Button[] buttons = new Button[Rows * Cols];
        int index = 0;
        for (int i = 0; i < Rows; i++)
        {
            for (int j = 0; j < Cols; j++)
            {
                Button b = new Button();
                b.Size = new Size(40, 55);
                b.Location = new Point(55 + j * 45, 55 + i * 55);
                b.BackColor = Color.Blue;
                buttons[index++] = b;
            }                
        }
        panel1.Controls.AddRange(buttons);
J.Robert
  • 17
  • 1

1 Answers1

2

As simple as this

int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
    int idx = rnd.Next(Rows * Cols);
    if (buttons[idx].BackColor == Color.Blue)
    {
        buttons[idx].BackColor = Color.Red;
        cnt++;
    }
}

You will use the Random class to choose an index value between 0 and 24 and use that index to select one of your blue buttons, if the selected button has a blue backcolor, change it to Red

By the way, this works because you don't really have a 2 dimension array here.
In case your array is declared as a 2 dimension array like here

Button[,] buttons = new Button[Rows, Cols];

then you need two random values at each loop, one for the row and one for the column

int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
    int row = rnd.Next(Rows);
    int col = rnd.Next(Cols);

    if (buttons[row, col].BackColor == Color.Blue)
    {
        buttons[row, col].BackColor = Color.Red;
        cnt++;
    }
}
Steve
  • 213,761
  • 22
  • 232
  • 286
  • That code is flawed, it can repeat the same index more than once. – Gusman Oct 07 '16 at 15:50
  • yes i really want a 2 dimension array...thanks a lot! i will try the second one. – J.Robert Oct 07 '16 at 22:09
  • With a two dimensions array you should also change how you add elements to the controls collection of the panel. Better add each single picturebox directly after creation. _panel1.Controls.Add(b);_ inside the loop – Steve Oct 07 '16 at 22:22