vb.net填充文本框在组合框中选择的索引随sql数据库更改

时间:2015-01-11 00:25:35

标签: sql vb.net combobox textbox sqldatareader

在我为编辑框选择了索引更改

时为填充文本框编写此代码之后

我收到此错误'对象引用未设置为对象的实例。',  我能做什么?

Private Sub participant1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles participant1.SelectedIndexChanged

    Try
        Dim cmd As SqlCommand = New SqlCommand()
        Dim datareader As SqlDataReader = Nothing
        If Class1.sqlcon.State = ConnectionState.Open Then
            Class1.sqlcon.Close()
        End If
        Class1.sqlcon.Open()
        Dim query As String
        query = " select * from tparticipant where namea = '" & participant1.Text & "'"
        cmd = New SqlCommand(query, Class1.sqlcon)
        While datareader.Read
            If datareader IsNot Nothing Then
                ID.Text = datareader.GetInt32("ID")
                total.Text = datareader.GetInt32("total")
            End If

        End While

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try`

2 个答案:

答案 0 :(得分:0)

您需要将cmd.ExecuteReader()分配给datareader。那就是NullReference来自哪里。

datareader = cmd.ExecuteReader()

答案 1 :(得分:0)

 Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
    Dim cmd As New SqlClient.SqlCommand
    Dim tbl As New DataTable
    Dim da As New SqlClient.SqlDataAdapter
    Dim reader As SqlClient.SqlDataReader
    Try
        cn.Open()
        Dim sql As String
        sql = "select * from Register"
        cmd = New SqlClient.SqlCommand(sql, cn)
        reader = cmd.ExecuteReader
        While reader.Read
            Dim id = reader.Item("cid")
            ComboBox1.Items.Add(id)
        End While
        cn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
    Dim cmd As New SqlClient.SqlCommand
    Dim tbl As New DataTable
    Dim da As New SqlClient.SqlDataAdapter
    Dim reader As SqlClient.SqlDataReader
    Try
        cn.Open()
        Dim sql As String
        sql = "select * from register where cid ='" + ComboBox1.Text + "'"
        cmd = New SqlClient.SqlCommand(sql, cn)
        reader = cmd.ExecuteReader
        While reader.Read
            TextBox1.Text = reader.Item("cname")
            TextBox2.Text = reader.Item("dob")

        End While
        cn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

End Sub

结束班