Reputation: 1973
I've a listbox that uses a dictionary as a datasource.
When I want to parse the listbox's selectedvalue to a int variable, it gives me a cast exception.
The dictionary~
Dictionary<int, string> AssetDictionary = new Dictionary<int, string>();
The listbox (lstAsset) datasource~
lstAsset.DisplayMember = "Value";
//lstAssetType.ValueMember = "Key"; //This should be lstAsset as corrected in the next line
lstAsset.ValueMember = "Key";
lstAsset.DataSource = new BindingSource(AssetDictionary, null);
The line where exception occurs~
int ush = (int)lstAsset.SelectedValue; //Specified cast is not valid.
Where am I doing wrong?
Upvotes: 1
Views: 3679
Reputation: 48568
Provide Value Member to correct control.
lstAsset.ValueMember = "Key";
and use
int ush = Convert.ToInt32(lstAsset.SelectedValue.ToString());
Upvotes: 3