Reputation: 21
I had this problem where if select query has rows, it will pass the data to datagridview, but if the query result has no rows, messagebox will appear containing "No records for this code."
this is my code:
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
Please edit my code. thanks
Upvotes: 0
Views: 63
Reputation: 15091
It is not an error for a reader to not have rows.
If Reader.HasRows Then
While Reader.Read
'Your code
Else
MessageBox.Show()
End If
How about putting your connection.Close in a Finally block so you are sure it will close even if there is an error. Check its state first.
Upvotes: 1