DataGridViewComboBoxCell value is not valid

JollyRoger picture JollyRoger · Jun 1, 2014 · Viewed 8.7k times · Source

Can someone explain to me how to add DataGridViewComboBoxCell to dataGridView? Code is something like this:

 foreach(....){

 DataGridViewComboBoxCell cmb = new DataGridViewComboBoxCell();
//cmb.item.add(....

dataGridView.Rows.Add(new object[] {cmb,name,surname});   } 

First cell in grid is type of DataGridViewComboBoxColumn, I tried with changing cmb to DataGridViewComboBoxColumn and still nothing.

I handeld DataError so i dont get "value is not valid" error, but my comboboxes in datagridview are empty.

Answer

JollyRoger picture JollyRoger · Jun 1, 2014

Ok, I solved the problem. It seems that you have to add values to cells step by step.

I'm going to give general explanation because it seems that a loot of people have problem with this. Let's say you have DataGridView with 3 columns, DataGridViewTextBoxCell, DataGridViewComboBoxColumn, DataGridViewCheckBoxCell in that order. Now, YOU HAVE to make make this three columns using Desinger or otherwise it wont work.

So now you want to add specific values to grid, each row representing lets say a person. In designer it looks like

          Name  PhoneNumberS   Married
  ..*.. |.....|..............|.........|.... 

So you want to add his name to textboxcell, list of phonenumbers to comboboxcell and to check checkboxcell if his married. And to repeat for each person you have in your list.

Here is pseudocode:

 foreach(Person p in people.getAll()){

/////MAKE NEW CELL FOR EACH VALUE
 DataGridViewTextBoxCell name= new DataGridViewTextBoxCell();
 name.Value = p.name;

 DataGridViewTextBoxCell phones= new DataGridViewTextBoxCell();

 foreach(Int Pnumber in p.numbers){
    phones.items.add(Pnumber);
  }

  DataGridViewCheckBoxCell ismarried = new DataGridViewCheckBoxCell();
         ismarried.Value = p.married;

 ///////// MAKE NEW ROW AND ADD CELLS
 DataGridViewRow row = new DataGridViewRow();
  row .Cells.Add(name);
  row .Cells.Add(phones);
  row .Cells.Add(ismarried );

   ///// ADD ENTIRE ROW TO DATA GRID
   dataGridView.Rows.Add(row);
   }

Just to repeat, you FIRST HAVE TO ADD COLUMNS TO GRID USING DESIGNER and when you add cells to row in code it HAS TO BE IN EXACLY SAME ORDER AS SEEN IN DESIGNER.