I want to retrieve data from 2 columns of my database table and bind those 2 columns to the combobox item index and item value properties respectively. I retrieve my data from the samples table of my database with this anonymous query:
var result = from obj in context.Samples
select new { obj.ID , obj.Name };
I want to set the default index value of each item in my combobox to obj.ID and the value of each respective combobox item to obj.Name so that rather than the items in my combo box having default values starting from 0, 1, 2…. their index values will have the value of obj.ID returned by my LINQ query and the actual value of the item will be obj.Name.
Sorry if this is a silly/amateurish question but I’ve spent a few hours trying to fix it and had no luck. Thanks in advance.
The
SelectedIndexproperty always goes from-1(no item is selected) tocount-1, you can’t change that. If you want to store theIDandNamefor each item in theComboBox, you can do that:Create non-anonymous type
Samplethat contains those two properties. Then assign (or bind) collection ofSamples to theComboBox‘sItemSourceand setDisplayMemberPathtoName. Then you can access theIDof the selected item using((Sample)yourComboBox.SelectedItem).ID.