3

Sorry if this is a silly question. I am quite new in this. How should i add combobox to datatable and then load it into the datagridview? Can this be done? And is this the best way? Tips and tutorials on how to do this are highly appreciated. Thank you in advance.

                string[] columnNames = dataTable.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
                DataTable dt = new DataTable();
                dt.Columns.Add("ColA");
                dt.Columns.Add("ColB");
                dt.Columns.Add("ColC");

                for (int i = 0; i < columnNames.Count(); i++)
                {
                    dt.Rows.Add();

                    dt.Rows[i][0] = columnNames[i].ToString();

                    //datatype
                    string sqlAllTables = "SELECT A, B FROM TB_LOOKUP";
                    DataSet ds;
                    ds = databaseManager.GetData(sqlAllTables);

                    DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
                    combo.DataSource = ds.Tables[0];
                    combo.DisplayMember = "A";
                    combo.ValueMember = "B";
                    dt.Rows[i][1] = combo;

                }

                dataGridView1.DataSource = dt;
MRu
  • 1,225
  • 7
  • 20
  • 44

1 Answers1

3

You can't add controls to DataTable.

If you want to show a combobox you will need to add it in datagridview and bind the combobox with data.

var column = new DataGridViewComboBoxColumn();
column.DataSource = ds.Tables[0];
column.DisplayMember = "A";
column.ValueMember = "B";
dataGridView1.Columns.Add(column);

Don't add third column dt.Columns.Add("ColC"); this will be the column in which we added the combobox above.

Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40