We help IT Professionals succeed at work.

# Generating a Unique Random Number VB.Net against a View

on
I have a piece  of VB.Net code that generates a random number and this value gets inserted into a row in a table. I use.

.Dim RandomNumber As Long
RandomNumber = RandomClass.Next(1000, 99999)

.no problem ..

Now I find out they don't want use the same number twice.. so I was thinking of creating a view of the table that shows all the numbers so far that was used.. and compare the newly generated number against the view ..if it exists..generate another number..if it doesn't exist in the table..then insert the value into the row in the table..

My view is called vRandom and hold 2 values the Rowid and iRandom

Just wondering what would be the best approach codewide
Any help or insight would be much appreciated..
Comment
Watch Question

## View Solution Only

Commented:
Why Random? Why not just the next sequential number? Much easier

Commented:
Is there a quick function for that?? Thinking about it that..next sequential number would be good..

Commented:
Try the code bellow, every time you call genRandNum() it will create a new unique random number.

class...

dim lstOldRands as new list(of long)

function checkIfWas(byval randNum as long) as boolean
for each num as long in lstOldRands
if randNum = num return true
next
return false
end function

function genRandNum as long

Dim RandomNumber() As Long
do while true
RandomNumber = RandomClass.Next(1000, 99999)
if not checkIfWas(RandomNumber)  then
return RandomNumber
end if
loop

end function
Commented:
oops, this one is fixed:

Dim lstOldRands As New List(Of Long)

Function checkIfWas(ByVal randNum As Long) As Boolean
For Each num As Long In lstOldRands
If randNum = num Then Return True
Next
Return False
End Function

Function genRandNum() As Long

Dim RandomNumber As Long
Do While True
RandomNumber = RandomClass.Next(1000, 99999)
If Not checkIfWas(RandomNumber) Then