2017-11-18 77 views
0

我有這個問題,如果選擇查詢有行,它會傳遞數據到datagridview,但如果查詢結果沒有行,messagebox將出現包含「沒有記錄爲此代碼。「顯示messagebox如果select查詢返回沒有行在vb.net

這是我的代碼:

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 

請編輯我的代碼。謝謝

回答

1

讀者沒有錯誤是不行的。

If Reader.HasRows Then 
While Reader.Read 
'Your code 
Else 
MessageBox.Show() 
End If 

如何把你的連接。關閉在最後一塊,所以你確信它會關閉,即使有一個錯誤。首先檢查它的狀態。

+1

哦,這只是一個簡單的解決方案,我的問題。感謝@mary它工作! – deitysha