ComboBox Question

N

Nikolay Petrov

I have a Combo box, binded to a dataset
With cmbCompany
.DataSource = dsSpecContact
.DisplayMember = "Companies.CompanyName"
.ValueMember = "Companies.CompanyID"
End With

What I want is to change the SelectedIndex of this Combo Box by using the
ValueMember or DisplayMemver values. I mean the "Companies.CompanyID" or
"Companies.CompanyName".

Some how I have to iterate through all the item in Combo Box and find which
item has ValueMember = "Companies.CompanyID" or DisplayMember =
"Companies.CompanyName" and select it.

Does anyone know how to do that, couse I can't figure it out



TIA
 
I

Imran Koradia

You could use a hashtable to store the index-ID mappings. something like:

For Each oCompany as Company In Companies
oHash.Add(oCompany.CompanyID, cmbCompany.Items.IndexOf(oCompany))
Next oCompany

When you need the index for a given CompanyID, you just do:

Dim index As Integer = CType(oHash.Item(CompanyID), Integer)

This would work fine for a fixed combobox where you're not going to be
adding-removing items at runtime. If you are going to be adding-removing
items, you'll need to update the hashtable to reflect these changes.
Also, for a combobox with not a lot of items (probably 10 to 15 items), it
wouldn't be too bad to loop through the combobox to retrieve the index since
populating and maintaining the hashtable does add some overhead anyway.

hope this helps..
Imran.
 
N

Nikolay Petrov

How to loop through the Combo Box items.
I know only the following method:
Dim itm as object
for each itm in ComboBox1.items
....
....
next

But this method does not provide me a way to access items properties,
becouse they are defined as Object
 
N

Nikolay Petrov

Also I don't understand

For Each oCompany as Company In Companies
oHash.Add(oCompany.CompanyID, cmbCompany.Items.IndexOf(oCompany))
Next oCompany

Could you please declare items oCompany, Company, Companies
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top