如果在数据库中找不到实体,如何防止出现错误



我制作了一个抽认卡应用程序,用户可以在其中编辑每个抽认卡的难度。

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

该按钮选择难度等于3的所有抽认卡,但如果没有记录,系统会产生错误。那么,如果没有这样困难的记录,我该如何获得它,以便系统生成消息呢?

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

最新更新