BernardWong BernardWong - 2 months ago 6
ASP.NET (C#) Question

Generate random numbers and insert into textfield

My objective is to generate random numbers and insert into 4 different textfields.

My Code Behind

protected void Generate_Click(object sender, EventArgs e)
{
TextBox1.Text = GenerateNumber().ToString();
TextBox2.Text = GenerateNumber().ToString();
TextBox3.Text = GenerateNumber().ToString();
TextBox4.Text = GenerateNumber().ToString();
}

private int GenerateNumber()
{
int i = 0;
Random rand = new Random();
i = rand.Next(0, 100);

return i;
}


But it then generates 4 same numbers in 4 textfields.

enter image description here

I want to have different numbers in different textfields without repeating.

Answer

There are a few ways in which you can generate different numbers keeping your code intact. Like, for example:

Passing an extra parameter in your method GenerateNumber(),

protected void Generate_Click(object sender, EventArgs e)
{
    TextBox1.Text = GenerateNumber(36).ToString();
    TextBox2.Text = GenerateNumber(21).ToString();
    TextBox3.Text = GenerateNumber(77).ToString();
    TextBox4.Text = GenerateNumber(9).ToString();
}

private int GenerateNumber(int a)
{
    int i = 0;
    Random rand = new Random();
    i = rand.Next(a, 100);
    return i;
}

or, as @Dmitry Bychenko told to create a static object of the Random class outside the GenerateNumber() method:

private static Random rand = new Random();
private int GenerateNumber()
{
    int i = 0;
    i = rand.Next(0, 100);
    return i;            
}