EDIT: While I still quite like my "individual digits" approach below, there's an easier way - just give a custom number format:
C#:
Random rng = new Random();
int number = rng.Next(1, 1000000000);
string digits = number.ToString("000000000");
Console.WriteLine(digits);
VB:
Dim rng As New Random
Dim number As Integer = rng.Next(1, 1000000000)
Dim digits As String = number.ToString("000000000")
Console.WriteLine(digits)
EDIT: As has been pointed out in the comments, a format string of D9 will also do the job:
Dim digits As String = number.ToString("D9")
Personally I'd have to look up exactly what that would do, whereas I'm comfortable with custom number formats - but that says more about me than about the code :)
Rather than generating a single number between 1 and 999999999, I would just generate 9 numbers between 0 and 9. Basically you're generating a string rather than a number (as numerically 000000000 and 0 are equivalent, but you don't want the first).
So generate 9 characters '0' to '9' in a Character array, and then create a string from that.
Here's some sample C# code:
using System;
class Test
{
static void Main(string[] args)
{
Random rng = new Random();
string digits = GenerateDigits(rng, 9);
Console.WriteLine(digits);
}
static string GenerateDigits(Random rng, int length)
{
char[] chars = new char[length];
for (int i = 0; i < length; i++)
{
chars[i] = (char)(rng.Next(10) + '0');
}
return new string(chars);
}
}
... and converting it to VB:
Public Class Test
Public Shared Sub Main()
Dim rng As New Random
Dim digits As String = Test.GenerateDigits(rng, 9)
Console.WriteLine(digits)
End Sub
Private Shared Function GenerateDigits(ByVal rng As Random, _
ByVal length As Integer) As String
Dim chArray As Char() = New Char(length - 1) {}
Dim i As Integer
For i = 0 To length - 1
chArray(i) = Convert.ToChar(rng.Next(10) + &H30)
Next i
Return New String(chArray)
End Function
End Class
One point to note: this code can generate "000000000" whereas your original code had a minimum value of 1. What do you actually want the minimum to be?