我遇到了这个问题,如果select查询有行,它会将数据传递给datagridview,但如果查询结果没有行,则会出现messagebox,其中包含&#34;此代码没有记录。&#34; < / p>
这是我的代码:
Private Sub txtScheduleID_KeyDown(sender As Object, e As KeyEventArgs) Handles txtScheduleID.KeyDown
If (e.KeyCode = Keys.Space) Then
Dim TextboxValue As String = RTrim(txtScheduleID.Text)
Dim vals = TextboxValue.Split(" ").Last()
sqlCon.Open()
Try
Dim QUERY As String
QUERY = "SELECT [Class Schedule LINE].SchedID, ListofSubjects.[Course No.], ListofSubjects.[Descriptive Title], Section.Section, Curriculum.[Lab.] + Curriculum.[Lec.], UtlyTIMETable.[FROM Time] +'-'+ UtlyTIMETable.[TO Time] + ' ' + UtlyDAY.Day + ' ' + UtlyRoom.Building + ' ' +UtlyRoom.[Room No.], UtlyInstructor.[Last Name] + ', ' + LEFT (UtlyInstructor.[First Name],1)+'.' " &
"FROM [Class Schedule LINE] INNER JOIN Curriculum ON [Class Schedule LINE].[Subject Code] = Curriculum.[Subject Code] INNER JOIN ListofSubjects ON Curriculum.SubjectID = ListofSubjects.SubjectID INNER JOIN Section ON [Class Schedule LINE].Section = Section.SectionID INNER JOIN UtlyTIMETable ON [Class Schedule LINE].TimeID = UtlyTIMETable.TimeID INNER JOIN UtlyDAY ON [Class Schedule LINE].DayID = UtlyDAY.DayID INNER JOIN UtlyRoom ON [Class Schedule LINE].RoomID = UtlyRoom.RoomID INNER JOIN UtlyInstructor ON [Class Schedule LINE].InstructorID = UtlyInstructor.IntructorID " &
"WHERE ([Class Schedule LINE].SchedID = '" + vals + "') "
CMD = New SqlCommand(QUERY, sqlCon)
Reader = CMD.ExecuteReader
While Reader.Read
table.Rows.Add(Reader.GetInt32(0), Reader.GetString(1), Reader.GetString(2), Reader.GetString(3), Reader.GetDecimal(4), Reader.GetString(5), Reader.GetString(6))
dgvSubjectsEnrolled.DataSource = table
End While
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
sqlCon.Close()
End If
End Sub
请编辑我的代码。感谢
答案 0 :(得分:1)
读者没有行不是错误。
If Reader.HasRows Then
While Reader.Read
'Your code
Else
MessageBox.Show()
End If
如何放置你的连接。关闭在一个Finally块中,这样即使出现错误,你也确定它会关闭。首先检查它的状态。