vb.net Visual Basic - 如果没有找到记录,如何显示消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20115738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Visual Basic - How to display message if no records found?
提问by Lorek Bryanson
I'm trying to display a "No records found" message box, but I have no idea how to write the code. Here is my code:
我正在尝试显示“未找到记录”消息框,但我不知道如何编写代码。这是我的代码:
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
Please advise how to write the IfElsecode, so that if there is no record, the "No record found" message will be shown. Thanks.
请告知如何编写IfElse代码,以便如果没有记录,将显示“未找到记录”消息。谢谢。
回答by Nadeem_MK
If i've understand your question, you need to check if you have data in your dataset before displaying in you textbox (code in your Button1_Click event). You can try this;
如果我理解您的问题,您需要在显示在文本框中之前检查数据集中是否有数据(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

