vb.net 在组合框上填充文本框选定的索引已更改为 sql 数据库

vb.net Filling Textbox On combobox Selected Index Changed with sql database

在我编写此代码以在组合框选择的索引更改时填充文本框

我遇到了这个错误 'Object reference not set to an instance of an object.', 我能做什么??

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`

您需要将 cmd.ExecuteReader() 分配给您的 datareader。那就是你的 NullReference 的来源。

datareader = cmd.ExecuteReader()
 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

结束Class