2013-11-21 134 views
0

我試圖顯示「找不到記錄」消息框,但我不知道如何編寫代碼。這裏是我的代碼:Visual Basic - 如果沒有找到記錄,如何顯示消息?

Public Class Form1 
    Dim cnn As New OleDb.OleDbConnection 

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click 
     Dim cmd As New OleDb.OleDbCommand 
     If Not cnn.State = ConnectionState.Open Then 
      cnn.Open() 
     End If 

     cmd.Connection = cnn 

     If Me.TextBox1.Text <> "" Then 
      cmd.CommandText = "INSERT INTO Student(StudentName, StudentID) " & _ 
       " VALUES('" & Me.TextBox1.Text & "','" & Me.TextBox2.Text & "')" 
       cmd.ExecuteNonQuery() 

      MsgBox("Record added") 
     Else 
      MsgBox("Please fill in required fields") 
     End If 

     cnn.Close() 
    End Sub 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load 
     cnn = New OleDb.OleDbConnection 
     cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\Testing.mdb" 

    End Sub 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     If Not cnn.State = ConnectionState.Open Then 
      cnn.Open() 
     End If 

     Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM Student WHERE StudentName='" & Me.TextBox1.Text & "'", cnn) 

     Dim dt As New DataTable 
     da.Fill(dt) 

     Me.TextBox3.Text = dt.Rows(0).Item("StudentName") 
     Me.TextBox4.Text = dt.Rows(0).Item("StudentID") 

     cnn.Close() 

    End Sub 
End Class 

請指教如何寫IfElse代碼,這樣,如果沒有記錄,「沒有找到記錄」消息將顯示。謝謝。

回答

3

如果我已經理解了您的問題,您需要先檢查數據集中是否有數據,然後再顯示在您的文本框(Button1_Click事件中的代碼)中。你可以試試這個;

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    If Not cnn.State = ConnectionState.Open Then 
     cnn.Open() 
    End If 

    Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM Student WHERE StudentName='" & Me.TextBox1.Text & "'", cnn) 

    Dim dt As New DataTable 
    da.Fill(dt) 

    // Assuming that at this stage, dt already contains the data 
    If dt.Rows.Count > 0 then 
     Me.TextBox3.Text = dt.Rows(0).Item("StudentName") 
     Me.TextBox4.Text = dt.Rows(0).Item("StudentID") 
    Else 
     MsgBox("No records found") 
    EndIf 

    cnn.Close() 

End Sub 
+0

這就是我要找的。非常感謝。 –

+0

你是最受歡迎的;) –

相關問題