user236501
user236501

Reputation: 8648

Random object returns the same result multiple times

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim s As New Staff
    Dim strConn As String

    strConn = ConfigurationManager.ConnectionStrings("ConnectionString").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT StaffID FROM Staff"
    Dim cmd As New SqlCommand(strSql, conn)

    Dim daMember As New SqlDataAdapter(cmd)
    Dim ds As New DataSet

    conn.Open()
    daMember.Fill(ds, "Staff")
    Dim i As Integer = ds.Tables("Staff").Rows.Count - 1
    For Each dr As DataRow In ds.Tables("Staff").Rows
        strSql = "Update CIOPassword SET CIPassword=@CI, COPassword = @CO WHERE StaffID=@id"
        Dim cmd2 As New SqlCommand(strSql, conn)
        Dim output1 As String = ""
        Dim output2 As String = ""
        Dim random As New Random()

        Dim val, val2 As Integer
        For j As Integer = 0 To 9
            val = random.[Next](1, 36)
            val2 = random.[Next](1, 36)
            output1 += ChrW(IIf(val <= 26, 64 + val, (val - 27) + 48))
            output2 += ChrW(IIf(val2 <= 26, 64 + val2, (val2 - 27) + 48))
        Next
        cmd2.Parameters.AddWithValue("@CI", output1)
        cmd2.Parameters.AddWithValue("@CO", output2)
        cmd2.Parameters.AddWithValue("@id", dr(0))
        cmd2.ExecuteNonQuery()
    Next
    GridView1.DataBind()
    conn.Close()
End Sub

Basically I am trying to update each record with 2 random numbers each time the button was clicked,my problem now is, the system will update the record but the data was wrong. Example, by right all data should be different (randomly string) but for some row it was updated with same data but in randomly, something row1 row2 row3 has exactly same data for column 1 and 2 then row 3 has distinct data, second time, row1 row2 same data row3 ro4 with different data. It is in random sequence. When I add a MsgBox to do testing in the For loop the data was updated correctly with all different data.

Upvotes: 0

Views: 153

Answers (2)

Steven Doggart
Steven Doggart

Reputation: 43743

Each time you create a Random object, it creates a new random sequence using the current time as the seed. If you create a bunch of Random objects at the same time, they will all have the same seed and therefore will generate the same sequence. As such, you should only create one Random object and reuse that same one until you are done. Don't keep creating new ones in the loop because if the loop runs too fast, they will end up not being "random".

Upvotes: 3

webdad3
webdad3

Reputation: 9080

Take a look at this site.

http://www.brettb.com/RandomNumbersInDotNet.asp

Your random.[Next] might be incorrect.

Upvotes: 0

Related Questions