在使用MySql调用Read()之前无法尝试访问字段

时间:2015-08-11 12:30:23

标签: mysql vb.net datagridview

我正在尝试运行此代码,但是当我点击数据网格视图时,这个错误总会弹出。

您认为这里的错误是什么?

Private Sub dgvRecords_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvRecords.CellClick
    Dim intID As Integer
    Try
        Integer.TryParse(dgvRecords.Item(0, dgvRecords.CurrentRow.Index).Value, intID)
        Dim dbQuery As String = "Select * from tblstudents where id = " & intID
        Dim dbConnection As New MySqlConnection(dbConString)
        Dim dbCmd As New MySqlCommand(dbQuery, dbConnection)
        Dim dbReader As MySqlDataReader
        dbConnection.Open()
        dbReader = dbCmd.ExecuteReader()

        txtStudID.Text = dbReader("id")
        txtLastname.Text = dbReader("lastname")
        txtFirstname.Text = dbReader("firstname")
        txtMiddlename.Text = dbReader("middlename")
        txtAddress.Text = dbReader("address")
        cmbGender.Text = dbReader("gender")
        txtContact.Text = dbReader("contact")
        cmbCivilStatus.Text = dbReader("civil_status")

        dbReader.Close()
        dbConnection.Close()
    Catch ex As Exception
        MsgBox("ERROR: " & ErrorToString(), MsgBoxStyle.Critical)
    End Try
End Sub

1 个答案:

答案 0 :(得分:0)

您收到该错误的原因是您没有在reader对象上调用Read()方法,并且没有哪个reader对象无法前进到结果集中的第一行以开始提取。这就是错误所说的。你应该这样做

While(dbReader.Read())
{
  txtStudID.Text = dbReader("id")
  txtLastname.Text = dbReader("lastname")
  .......
}