Friday, September 16, 2011

.NET Framework 4: Unable to cast object of type 'system.string' to type


For example you are binding pricelist-objects to a combobox in WinForms application like this

cmbPricelist.DataSource = BL.GetPricelists();
cmbPricelist.ValueMember = "PricelistCode";
cmbPricelist.DisplayMember = "PricelistName";

and later you trying to get selected item from combobox like this

Pricelist p = (Pricelist)cmbPricelist.SelectedValue;

you might get an error "Unable to cast object of type 'system.string' to type..."


If you are using .NET Framework 4 Client profile ComboBox.SelectedValue method returns object (in this example Pricelist).

But if you are using .NET Framework 4 Full profile ComboBox.SelectedValue method returns ValueMember as String