C # Winforms DatagridviewCombobox Exception String cannot be converted to class

I encounter an exception when choosing a new value from the datagridviewcombobox control (drop down menu) built into the datagridview. The layout is populated with a BindingSource, which is populated with instances of my class. I can correctly display the options in the menu and select one, but changing the focus to the new control (making the change I suppose) raises an exception: Invalid Sent from System.String to myclass. The stack trace (if Im uses this word on the right) indicates that the source was

System.Windows.Forms.DataGridView.PushFormattedValue cascading to System.Convert.DefaultToType

Below is a more detailed explanation (sorry for so long, but I wanted to make it reproducible):

I have an empty class called "Busy", with no properties (the problem exists when Oknatan also has the "String Name" property so that it doesn't exist). I have a BindingSource called OccupantSource, with its DataSource pointing to Occupant.

I also have a class called Car, with one Occupant property called Driver.

In my Form_Load (), I call UserantSource.AddNew () twice and call CarSource.AddNew () once.

I have a DataGridView control whose data source is CarSource (BindingSource consisting of cars). DGV has a single column displaying the Driver property for cars in CarSource. This is a DataGridViewComboBoxColumn with the DataPropertyName parameter for the driver.

So, I want to show machine rows in Datagridview, and one of the columns is a combobox, which I can output and select a driver from existing instances. But I get an exception.

Am I misunderstanding something? Can you use class instances to populate a DataGridViewComboBox?

+4
source share
1 answer

I ran into the same problem and scratched my head using my google-fu for hours trying to solve it. This connection helped me finally give me a good explanation. http://www.pcreview.co.uk/forums/datagridview-combobox-column-error-listing-objects-t2344961.html

As I fixed this, it was necessary to change the DisplayMember. I got a reference to "I" in the class that returned 'this' - I used this for DisplayMember and ValueMember, thinking that this would just be the ToString () property from DisplayMember.

Reading your explanation, maybe you did not have DisplayMember and ValueMember? If so, try setting them correctly (and don't use the 'this' link for the display element!), And that might fix it.

+5
source

All Articles