Hi, the following code generates the exception "Object reference not set to an instance of an object" when viewed in the browser. I have read that the most common causesof this error are not declaring the variables before usingthem, bad scoping, and not using the key word New wheninstantiating. I thought I have made sure that the afore mentionedcauses are not the causes of the error I'm getting but obviously thereis something wrong with my code. Please help me identify thecause of the exception, I just can not see what it could be at themoment. Thank you in advance for your help.
Dim myCon As OdbcConnection
Dim i As Integer
Dim cmd As OdbcCommand
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items(i).Selected Then
myCon = New OdbcConnection("Driver={MySQL ODBC 3.51Driver};Server=myServer;Database=myDatabase;User=myUser;Password=myPW;Option=3;")
cmd = New OdbcCommand("SELECT * FROM myTable where Professions = '"& ListBox2.Items(i).Text & "'")
End If
Next
myCon.Open()
cmd.Connection = myCon
Dim ds As New DataSet
Dim ad As New OdbcDataAdapter(cmd)
ad.Fill(ds)
Me.ListBox2.DataSource = ds
Me.ListBox2.DataTextField = "Professions"
Me.ListBox2.DataBind()
try changing to:
Dim myCon As new OdbcConnection(yourConnectionString)
Dim cmd As new OdbcCommand(yourQuery)
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items(i).Selected Then
myCon = New OdbcConnection("Driver={MySQL ODBC 3.51Driver};Server=myServer;Database=myDatabase;User=myUser;Password=myPW;Option=3;")
cmd = New OdbcCommand("SELECT * FROM myTable where Professions = '" & ListBox2.Items(i).Text & "'")
End If
Next
[If no item is selected is selected in the ListBox2, then myCon will be a null value, so what you need to do is to make sure myCon is checked against this situation before calling the open function.
Something like
If myCon is Not Nothing (I am not a vb guru, but you get the idea).
myCon.Open()
0 comments:
Post a Comment