Victor.Wiedemann - 3 months ago 9

Vb.net Question

Hello I am trying to create a function in vb.net to create a randomly generated color to highlight rows in a ListView on a form. The input to the code is SlaveID which is a Byte. The problem I am having is that if I input the Same SlaveID in multiple times, I will always get the same color output. Since Rnd takes in current time to make the number more random, the colour output changes every time I call this function even though my input value stays the same. Is there a random number generator that is not effected by time that would be an easy replacement for Rnd?

`Private Function GetColourForRow(ByVal SlaveID As Byte)`

Dim ListViewItemColour As New ListViewItem

Dim upperbound As Byte = 255

Dim lowerbound As Byte = 100

Dim ColourA As Int16 = CInt(Math.Floor((upperbound * 2 - lowerbound + 1) * Rnd(SlaveID) + 2)) + lowerbound

Dim ColourR As Int16 = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd(SlaveID))) + lowerbound

Dim ColourG As Int16 = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd(SlaveID + 5))) + lowerbound

Dim ColourB As Int16 = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd(SlaveID + 15))) + lowerbound

Return ListViewItemColour.BackColor

End Function

Answer

To generate the same pseudo random numbers each time, you can `Randomize`

with the same seed:

```
Private Function GetColourForRow(ByVal SlaveID As Byte)
Static seed# = Rnd() ' Static values will be set only the first time the function is called and will stay the same
Randomize(seed)
' the rest of the code
```