how to use dynamically change the data source of DataGridViewComboBoxCell

Junfeng Liang 156 Reputation points
2021-11-26T10:06:18.317+00:00

I am trying make a datagridview with two comboboxcolumn. When column[1] is selected, the data source of the column [2] will change. I setup the design of the datagridview with the design windows and then write the code

Here is a part of my code for adding data to the datagridview

//parites is a list of class Party
DataGridViewComboBoxCell CobParty= new DataGridViewComboBoxCell();
CobParty.DataSource = parties;
CobParty.DisplayMember = "Name";
CobParty.ValueMember = "ID";

//members is a list of member of class Party
DataGridViewComboBoxCell CobGovernor = new DataGridViewComboBoxCell();
CobGovernor.DataSource = Party.members
CobGovernor.DisplayMember = "Name";
CobGovernor.ValueMember = "ID";

foreach(var item in states)
{
 dataGridView1.Rows.Add( item. Name, CobParty, CobGovernor);
}

It threw me an error saying that: "DataGridViewComboBoxCell value is not valid"

Is it because I did not set the value type for the columns with combobox? If so, how can I do it through coding? I am new to C#. Please give me some detail. Thank you.

Developer technologies | C#
{count} votes

Accepted answer
  1. Junfeng Liang 156 Reputation points
    2021-12-02T02:12:37.67+00:00

    I finally work around it by placing combobox on top of the desire cell of the datagridview. Thank you anyway.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-11-26T11:24:46.707+00:00

    You can't load a DataGridViewComboBox for each row as you, DataPropertyName and have, instead load the DataGridView.DataSource then assign each DataGridViewComboBox following properties DisplayMember, ValueMember and DataSource.

    See the following project for how to do the above.

    • Second and last columns are DataGridViewComboBoxColumn

    152877-datagridviewcombobox1.png


  2. Junfeng Liang 156 Reputation points
    2021-11-26T19:39:22.92+00:00

    I learn something from this link
    https://stackoverflow.com/questions/37846950/c-sharp-runtime-error-datagridviewcomboboxcell-value-is-not-valid

    It ran through. But it gave me something wired. Instead of changing the column I want to become combobox. It looks like this:

    152930-image.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.