Click here to Skip to main content
15,885,653 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I’m trying to write code for a form which will associate a comboBox with a value from a table.
The comboBox uses a DataSet as its source. This has two fields, a Company ID number and the Company Name:
comboBox3.DataSource = CompaniesDS.Tables[0];
comboBox3.ValueMember = "CompanyID";
comboBox3.DisplayMember = "CompanyName";

The form is populated from a table and shows detail of the one job, one field of which contains the CompanyID.
When the record is read from the database it therefore has a value
(myReader["CompanyID"].ToString())

And I want it to position the SelectedIndex of the comboBox where the comboBox.ValueMember is the same as the job CompanyID.
FindString appears to search the DisplayMember, can I make it search the ValueMember?

What I have tried:

Tried FindStringExact
Tried FindString
Tried to loop through the contents of the ComboBox list.
Posted
Updated 10-Oct-21 22:01pm
Comments
PIEBALDconsult 11-Oct-21 10:42am    
Don't search the ComboBox. Search the DataSet or make another object -- maybe a Dictionary -- to search.

1 solution

This is the way I handled this in the past:

1) assuming the first column is the Int32 'Id number, and the ComboBox ValueMember is bound to 'Id:
DataRow drow = dtbl1.Rows.Cast<DataRow>().First((DataRow row) => row.ItemArray[0].Equals(4));
datacomboBox.SelectedIndex = (int) drow.ItemArray[0];
I consider it ugly :), and, today, would look for a better way.

If this is irrelevant to your goal, let me know, and i'll delete this post.
 
Share this answer
 
v2
Comments
ormonds 11-Oct-21 20:55pm    
Found an answer, but probably uglier. I have added another (invisible) combobox which contains the CompanyID, matched that to the person's CompanyID and then set the SelectedIndex of comboBox3 to the same as the new comboBox.
Thanks for your help.
BillWoodruff 12-Oct-21 14:07pm    
In my own code in the past I've mapped a DataTable to a Dictionary where the Keys were of the DisplayMember Type, and Values of the ValueMember Type. That makes lookup easy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900