Filling a lookup field with a data reader

  • Thread starter Thread starter Woody Splawn
  • Start date Start date
W

Woody Splawn

I have some code that I put in the Before_Dropdown event of a combobox field
on a winform. It works but only because I am making use of a public
boolean variable called IveFilledCompanys. The code follows:

If IveFilledCompanys = False Then
SqlConnection1.Open()
Dim SqlReader As System.Data.SqlClient.SqlDataReader
SqlReader = SqlCommand1.ExecuteReader()
While SqlReader.Read
cboCompanys.Items.Add(SqlReader.Item("Company"))
End While
SqlReader.Close()
SqlConnection1.Close()
IveFilledCompanys = True
End If

I would like to keep the use of public variables to a minimum. I wonder if
there is another way to write this code without the variable. Basically, I
would like the code (upon arrival on the combobox field) to fill the
combobox with data if it has not already been filled. I thought perhaps
something like the following would work, again, this is in the
BeforeDropDown event.

Dim iCount As Integer = cboCompanys.DataBindings.Count()
If iCount <= 1 Then
... fill the table code
Else
MsgBox("It's already been filled. Do nothing")
End If

However, I find that when running my code iCount never equals anything but
1.

Anyone have any ideas on how I can accomplish what I want?
 
New here, but why dont you just change your code to read

That was a good suggestion. Thank you.
 
Hi Woody,

The iCount never changes because you didn't add any Databindings to the
ComboBox. The DataBindings.Count property increases only when you use
DataBindings.Add() method to add a binding to a data source. When you
called cboCompanys.Items.Add(), you didn't make any changes to the
DataBindings property. Please try to use iCount = cboCompanys.Items.Count,
and check if iCount >0 before adding items to it.

If anything is unclear, please feel free to reply to the post.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
Back
Top