问题
after i programming this code for fill text-box when combo-box selected Index changed
i got this error 'Object reference not set to an instance of an object.', whats can i do ??
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`
回答1:
You need to assign the cmd.ExecuteReader()
to your datareader
. Thats where your NullReference
is coming from.
datareader = cmd.ExecuteReader()
回答2:
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
End Class
来源:https://stackoverflow.com/questions/27882682/vb-net-filling-textbox-on-combobox-selected-index-changed-with-sql-database