3

How to add items to the drop down list of a combo box in a datagridview?

demonplus
  • 5,613
  • 12
  • 49
  • 68

4 Answers4

2

The DataGridViewComboBoxColumn has an Items-Property which you can use like this:

DataGridViewComboBoxColumn theColumn = (DataGridViewComboBoxColumn)this.YourDataGrid.Column("YourColumn");
theColumn.Items.Add("NewItem");
theColumn.Items.Add("NewItem2");

Edit: Do not forget that you need to cast the Column to the right type, because they're a of the generic DataGridViewColumn-Type.

Bobby
  • 11,419
  • 5
  • 44
  • 69
1

There are various ways of achieving your goal, here's one of them, that just might do the trick

This method consists of two steps.

1) Create a ComboBox & Add contents to it

2) Add the Items if The ComboBox to your DataGridComboBox

Step 1)

ComboBox CB= new ComboBox();
CB.Items.Add("A"); 
CB.Items.Add("B");
CB.Items.Add("C");
CB.Items.Add("D");
CB.Items.Add("E");

Step 2)

((DataGridViewComboBoxColumn)MyDataGrid.Columns["MyDataGridColumnName"]).DataSource = CB.Items ;
VAR
  • 73
  • 6
1

if you have a combobox in the DataGridView, you can add items in to your combobox that in DataGridView like this:

  1. Create DataGridViewComboboxCell object

  2. Add your items into your DataGridViewComboboxCell object that created

  3. Assign created object to your empty combobox

Step 1

DataGridViewComboBoxCell cmbbox = new DataGridViewComboBoxCell();

Step2

cmbbox.Items.Add("A");
cmbbox.Items.Add("B");
cmbbox.Items.Add("C");

Step3

int emptyComboBoxRowsIndex = 0;//you change with your index;
int emptyComboBoxCellIndex = 0;//you change with your index;
DataGridView1.Rows[emptyComboBoxRowsIndex].Cells[emptyComboBoxCellIndex] = cmbbox;
0

Linq To Sql

DataClasses1DataContext dc = new DataClasses1DataContext();

Add Grid : gvRecord

Linq Query

  var details = (from x in dc.Details
                 orderby x.Datetime descending
                 select x).ToList();



  var combocolumnA = new DataGridViewComboBoxColumn();
                    combocolumnA.HeaderText = "ID";
                    combocolumnA.ValueMember = "id";
                    combocolumnA.DataSource = details;
                    gvRecord.Columns.Add(combocolumnA);
                    combocolumnA.Width = 100;

  var combocolumnB = new DataGridViewComboBoxColumn();
                    combocolumnB.HeaderText = "Name";
                    combocolumnB.ValueMember = "Name";
                    combocolumnB.DataSource = details;
                    gvRecord.Columns.Add(combocolumnB);
                    combocolumnB.Width = 150;
Ahsan
  • 3
  • 7