我正在尝试显示“找不到记录”消息框,但我不知道如何编写代码。这是我的代码:
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
请告知如何编写If
Else
代码,以便在没有记录的情况下,将显示“未找到记录”消息。感谢。
答案 0 :(得分: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