Set value to ComboBoxCell in DataGridView

3k views Asked by At

I want to set a value for a cell that is actually a comboboxcell. I done it for my another project but now the same way, doesnt work!!

here is my code

        //dgExcel is my datagridview

        var cmb = (DataGridViewComboBoxColumn)dgExcel.Columns[1];
        cmb.DataSource = sucTurleri; //its a list 
        cmb.DisplayMember = "SucTuru";
        cmb.ValueMember = "Id";

and this code is adding row to the grid

var Konumlar = ExcelYardimcisi.KonumlariExceldenAl(dg.FileName);

foreach (var konum  in Konumlar)
{

  dgExcel.Rows.Add(konum.KonumAdi, sucTurleri[0].SucTuru, DateTime.Now.ToShortDateString());
}

but i got an error and i used this

 foreach (var konum  in Konumlar)
 {

  dgExcel.Rows.Add(konum.KonumAdi, null, DateTime.Now.ToShortDateString());

  DataGridViewComboBoxCell cbox = (DataGridViewComboBoxCell)dgExcel.Rows[dgExcel.Rows.Count - 1].Cells[1];

   cbox.Value = sucTurleri[0].SucTuru;

}

and the error is

enter image description here

1

There are 1 answers

1
Arin Ghazarian On BEST ANSWER

Your data binding part is pretty OK. The problem is with dgExcel.Rows.Add() method. Here is a sample code:

    List<Item> items = new List<Item>();
    items.Add(new Item() { Name = "One", Id = 1 });
    items.Add(new Item() { Name = "Two", Id = 2 });
    var cbo = dataGridView1.Columns[1] as DataGridViewComboBoxColumn;
    cbo.DataSource = items;
    cbo.ValueMember = "Id";
    cbo.DisplayMember = "Name";

    dataGridView1.Rows.Add("test", items[1].Id);
    ...

    public class Item
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }

Because the DataGridViewComboBoxColumn is data bound, you have to set the value by ValueMember, in my case items[1].Id. You have to to this in your code as well.