Home > Software engineering >  How to prevent an error if an entity in a database is not found
How to prevent an error if an entity in a database is not found

Time:11-12

I made a flashcard application where the user can edit the difficulty of each flashcard.

Private Sub btnHard_Click(sender As Object, e As EventArgs) Handles btnHard.Click
    Dim sqlstring As String = "select * from flashcards where Difficulty = 3" 'Select from flashcard table where difficulty = 3
    dataadapter = New OleDb.OleDbDataAdapter(sqlstring, connection)
    dt.Clear() 'Clears datatable
    dataadapter.Fill(dt) 'Fills datatable

    Dim index = rand.Next(dt.Rows.Count) ' generates index in the range 0 .. Count - 1
    If txtBack.Visible = True Then
        txtFront.Text = dt.Rows(index)(2).ToString()
        txtBack.Visible = False
        txtBack.Text = dt.Rows(index)(3).ToString()
    Else
        MsgBox("Please first reveal the back of the flashcard")
    End If

End Sub

This button selects all the flashcards where difficulty is equal to 3 but if there are no records than the system produces an error. So how would I get it so the system produces a message if there are no records with that difficulty?

CodePudding user response:

Private Sub btnHard_Click(sender As Object, e As EventArgs) Handles btnHard.Click
    Dim sqlstring As String = "select * from flashcards where Difficulty = 3" 'Select from flashcard table where difficulty = 3
    dataadapter = New OleDb.OleDbDataAdapter(sqlstring, connection)
    dt.Clear() 'Clears datatable
    dataadapter.Fill(dt) 'Fills datatable

    If dt.Rows.Count = 0 Then 'If record is not found in the database
        MsgBox("There are no more flashcards inside this deck")
        Exit Sub 'Code continus running if record is found
    End If

    Dim index = rand.Next(dt.Rows.Count) ' generates index in the range 0 .. Count - 1
    If txtBack.Visible = True Then 'If the back of the flashcard is shown
        txtFront.Text = dt.Rows(index)(2).ToString() 'Displays a random record in the third column (front of flashcard)
        txtBack.Visible = False 'Does not display the back of the flashcard
        txtBack.Text = dt.Rows(index)(3).ToString() 'Displays a random record in the fourth column ()
    Else 'If the user has not pressed the reveal button before
        MsgBox("Please first reveal the back of the flashcard")
    End If
End Sub
  • Related