My random number generator does not create a new value in my C # loop

advertisements

This question already has an answer here:

  • Random number generator only generating one random number 7 answers

I am using c# to try and populate a datagridview with random numbers but for some reason I keep getting the same value in all the cells.

    public int GenerateRandomNumber()
    {
        const int minimumNumber = -9;
        const int maximumNumber = 15;
        var random = new Random();
        var randomNumber = random.Next(minimumNumber, maximumNumber);
        return randomNumber;
    }

gameBoard is the datagrid view.

    private void populateButton_Click(object sender, EventArgs e)
    {
        CreateGameBoard((int)columnsNumericUpDown.Value,(int)rowsNumericUpDown.Value);
        gameBoard.RowTemplate.Height = gameBoard.Height/gameBoard.RowCount;
        foreach (DataGridViewRow row in gameBoard.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {

                cell.Value = GenerateRandomNumber();
            }
        }
    }


Random is initialized using the clock which means that you will get the same value multiple times.

So, instead of re-creating Random instance you should keep a single Random instance and keep using Next on the same instance. If you have multiple threads then you should read this for locking solution

This is what you need.

private Random random = new Random();
const int minimumNumber = -9;
const int maximumNumber = 15;
public int GenerateRandomNumber()
{
    var randomNumber = random.Next(minimumNumber, maximumNumber);
    return randomNumber;
}