datagridview with datasource and combobox

35.5k views Asked by At

I have a datagridview with a datasource attached to it made of a custom datatable:

DataTable: 0 = Dictionary 1 = string 2 = string

the datagridview is editable, however for column 0 I need to show a combobox instead of a text field. How do I go about achieving this?

internal Dictionary<int, string> products_list = new Dictionary<int, string>();
products_list.Add(0, "Test Product 1");
products_list.Add(1, "Test Product 2");


lines.Columns.Add(new DataColumn("Product", products_list.GetType()));
lines.Columns.Add(new DataColumn("QTY", typeof(int)));
lines.Columns.Add(new DataColumn("Description", typeof(string)));

dgvQuoteLines.DataSource = lines;
dgvQuoteLines.Columns[0].Visible = false;

* UPDATE * I have now managed to add the combobox to the datagridview but sadly the datasource isn't working!

DataGridViewComboBoxColumn colbox = new DataGridViewComboBoxColumn();
colbox.DataPropertyName = "0";
dgvQuoteLines.Columns.Add(colbox);
3

There are 3 answers

3
Derek On BEST ANSWER

I think this is what you want:

DataGridViewComboBoxColumn colbox = new DataGridViewComboBoxColumn();
colbox.DataSource = products_list.ToList();
colbox.ValueMember = "Key";
colbox.DisplayMember = "Value";
dgvQuoteLines.Columns.Add( colbox );

Look at the DataGridViewComboBoxColumn class.

3
Derek On

colBox.DataSource = products_list.Values.ToList();

?

What do you want to show up in the combobox?

1
PoorPeople On

Try this:

          string str4 = "select * from tblDepartment";
         DataGridViewComboBoxColumn colbox = new DataGridViewComboBoxColumn();
         colbox.DataSource = clsKetnoi.clsKetnoi.LayDuLieu(str4);
         colbox.Name = "Department";
         colbox.HeaderText  = "Department";
         colbox.ValueMember = "IDDepartment";
         colbox.DisplayMember = "DepartmentName";
         dgvDevice.Columns.Add(colbox);