mercredi 16 mars 2022

Do While Loop doesn't stop looping in VB.net

I'm trying to generate a random number that's not in the database. If the randomly generated number happens to already be in the database, a message box appears saying the number exists. When you click Ok, it generates another number and if it's still in the database, it will repeat the same process. With my code, it keeps showing the message box and generating a number even after it has already generated a number that's not in the database. This is my code:

Private Sub BtnOrder_Click(sender As Object, e As EventArgs) Handles BtnOrder.Click
    Dim rand As New Random
    Dim num As Integer

    num = rand.Next(1, 30)
    TxtOrder.Text = "#" + num.ToString("0000")
    BtnOrder.Enabled = False

    Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Sales.accdb;")
    Dim command As New OleDbCommand("SELECT [Order No] FROM [Table1] WHERE [Order No] = orderno", connection)
    Dim orderParam As New OleDbParameter("orderno", Me.TxtOrder.Text)
    command.Parameters.Add(orderParam)
    command.Connection.Open()
    Dim reader As OleDbDataReader = command.ExecuteReader()
    Do While reader.HasRows = True
        If reader.HasRows = False Then
            Exit Do
        End If
        MessageBox.Show("Order number exists.", "Invalid Order Number")
        num = rand.Next(1, 30)
        TxtOrder.Text = "#" + num.ToString("0000")
    Loop
    command.Connection.Close()
End Sub



Aucun commentaire:

Enregistrer un commentaire