• 0

[C#] ComboBox Specified Cast Not Valid!


Question

This is the code:

cmbBalSheetCat.Items.Clear();
cmbBalSheetCat.DataSource = dtResults;
cmbBalSheetCat.ValueMember = "BalanceSheetCategoryID";
cmbBalSheetCat.DisplayMember = "BalanceSheetCategoryName";
cmbBalSheetCat.SelectedIndex = -1;

It errors on setting the .ValueMember saying the 'Specified cast is not valid'.

dtResults is populated like so:

dtResults = new DataTable();
dtResults.Columns.Add("BalanceSheetCategoryIDddtResults.Columns.Add("BalanceSheetCategoryNameddtResults.Columns.Add("BalanceSheetCategoryOrderforeach( BalSheetCatData objBalSheetCatData in this.Values )
{
	DataRow dtRow = dtBalSheetCats.NewRow();
	dtRow["BalanceSheetCategoryID"] = objBalSheetCatData.BalanceSheetCategoryID;
	dtRow["BalanceSheetCategoryName"] = objBalSheetCatData.BalanceSheetCategoryName;
	dtRow["BalanceSheetCategoryOrder"] = objBalSheetCatData.BalanceSheetCategoryOrder;
	dtResults.Rows.Add( dtRow );
}

I dont understand why im getting this error. I have similar code for a combo on a different form that works fine!!

Do i need to specify column types or something? If so, how comes it works fine without it on other forms and not this one?

Any ideas?

Link to comment
https://www.neowin.net/forum/topic/416380-c-combobox-specified-cast-not-valid/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

__________________________________________________________________

Ah ok... just found its not the .ValueMember line that it is erroring on. Its because the combo has an associated _SelectedIndexChanged() method and its erroring inside there.

To fix the problem, ive used a boolean value to store whether the combo data has been loaded and the _SelectedIndexChanged() only executes code when that boolean is true.

But this seems somewhat feeble... is there a better way of doing this? A setting ive missed?

  • 0

Just a quick note to give u a helping hand, Databinding an Array of objects or values (MyObject[]) isn't the same as binding an ArrayList of MyObject for example. The former been non enumerable by default and wont store the combobox wont store ValueMember.

Ie.

MyObject[] objMyObjects = null;

... initialize myobjects array...

Combobox1.DisplayMember = "Description";

Combobox1.ValueMember = "ID";

Combobox1.DataSource = objMyObjects;

this will cause the Combobox1 to not hold the selected objects value as it isnt Enumerable. A nice way around this would be too simply to do following...

MyObject[] objMyObjects = null;

... initialize myobjects array...

Combobox1.DisplayMember = "Description";

Combobox1.ValueMember = "ID";

Combobox1.DataSource = new ArrayList(objMyObjects);

This will enable enumeration for ur combobox, and as such it will hold the values correctly.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.