Here is a code where I add value to datagridview from datatable. The "First" and "Third" column of the datagridview have been filled with data from the datatable. The problem is for the "Second" and the "Forth" column, as I have to make it a combobox for the user to choose. Each combobox has default value which is "columnDefaultValue".
string sqlMatchedData = "SELECT colA, colB, colC, colD " +
"FROM TB_LOOKUP_COLUMN "
ds = databaseManager.GetData(sqlMatchedData);
dataGridView1.ColumnCount = 4;
dataGridView1.Columns[0].Name = "First";
dataGridView1.Columns[1].Name = "Second";
dataGridView1.Columns[2].Name = "Third";
dataGridView1.Columns[3].Name = "Forth";
foreach(DataRow row in ds.Tables[0].Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = row[0].ToString();
dataGridView1.Rows[n].Cells[2].Value = row[3].ToString();
string columnDestination = row[1].ToString();
string columnType = row[2].ToString();
comboboxDestinationColumn(columnDefaultValue);
}
How can I create combobox using the datatable and bind it to the specific cell?
private void comboboxDestinationColumn(string columnDefaultValue)
{
string sqlLookupColumn = "SELECT colALookUp, colBLookUp FROM TB_LOOKUP_COLUMN";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Destination";
combo.Name = "combo";
foreach(DataRow row in dsColumn.Tables[0].Rows)
{
//populate combobox with data from datatable with defaul value columnDefaultValue
}
}
EDITED
I have found the way to add the combobox to datagridview. But i still lacking the way on how can i set the default value for each combobox based on the variable columnDefaultValue
private void comboboxDestinationColumn(string columnDefaultValue, int n)
{
string sqlLookupColumn = "SELECT colALookUp, colBLookUp FROM TB_LOOKUP_COLUMN";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxCell comboboxColumn = new DataGridViewComboBoxCell();
foreach (DataRow row in dsColumn.Tables[0].Rows)
{
comboboxColumn.Items.Add(row[1].ToString());
}
dataGridView1.Rows[n].Cells[1] = comboboxColumn;
}
I'm trying to find something like:
comboboxColumn.Selected = true;
What is the proper way to do this?
comboboxColumn.Value = comboboxColumn.Items[0] //or whichever of all the items you want
. P.S.: It's a bad practic to name aDataGridViewComboBoxCell
like "comboboxColumn"... – D. Petrov