I have a DataGridView with a Column already defined as ComboBox. How do I add items to that Column Combobox so that they are available in that column for each new row?
I have tried everything I could think of or find on the web. Here's the latest attempt:
[![ static DataGridViewComboBoxColumn dgvCmb = new DataGridViewComboBoxColumn(); static DataGridViewComboBoxCell dgvCmbCell = new DataGridViewComboBoxCell(); DataTable dt = new DataTable();
private void frmReporting_Load(object sender, EventArgs e)
{
dt = Populate("SELECT DISTINCT OperatorName FROM tblOperator WHERE OperatorName NOT LIKE '*%' AND Active='1' ORDER BY OperatorName");
dgvCmbCell = FillComboBox();
dgvReports[1, 0] = dgvCmbCell;
}
private DataGridViewComboBoxCell FillComboBox()
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
//DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
ArrayList row = new ArrayList();
foreach (DataRow dr in dt.Rows)
{
row.Add(dr[0].ToString());
}
combo.Items.AddRange(row.ToArray());
return combo;
}
private DataTable Populate(string sqlCommand)
{
myConnection.Open();
SqlCommand command = new SqlCommand(sqlCommand, myConnection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
myConnection.Close();
return table;
}
Well… I am going to make a few assumptions here since you did not supply all the info needed. In the future you may get better results if you supply all the info that applies to your question as opposed to helpers having to ask these obvious questions.
First you show a picture of a grid that has a column named “Name.” This looks like a combo box column given the little down arrow. However, you do not show the code that “adds” that column to the grid. SO, I will assume two things here…
dgvReportsNameis “OperatorName.”If this is the case, then you could change your current code to the code below to add the
DataTabledtas aDataSourceto the EXISTING column named “OperatorName” in the grid nameddgvReports…Considering that the
DataGridViewComboBoxColumnalready exist in thedgvReports, then, it is unnecessary to “create” another combo box column or any combo box cells as your current code does.If the
Nameof the combo box column in the grid is NOT named “OperatorName” then you need to change the code to the whateverNamethe combo box column name has in the grid…