I want to generate an unique 4 digit random number. This is the below code what I have tried:
Code for generating random number
//Ge
int NoDigits = 4;
Random rnd = new Random();
textBox2.Text = rnd.Next((int)Math.Pow(10, (NoDigits - 1)), (int)Math.Pow(10, NoDigits) -1).ToString();
//Generate RandomNo
public int GenerateRandomNo()
{
int _min = 1000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
you need a 4 digit code, start with 1000
Use this code instead:
private Random _random = new Random();
public string GenerateRandomNo()
{
return _random.Next(0, 9999).ToString("D4");
}
0 is the same as 0000.
241 is the same as 0241.
You could format the integer to a string with a leading zero.
Just one line code
int num = new Random().Next(1000, 9999);