Samik Sengupta
Samik Sengupta

Reputation: 1973

Parsing SelectedValue of a ListBox to int using C#.NET

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

Answers (1)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Provide Value Member to correct control.

lstAsset.ValueMember = "Key";

and use

int ush = Convert.ToInt32(lstAsset.SelectedValue.ToString());

Upvotes: 3

Related Questions