C# – Converting Column in DataGridView into a ComboBox

cdatagridviewwinforms

I have a WinForms application written in C# in which I have a DataGridView bound to a DataSource populated from a SQL Database.

My code is as follows –

string sqlText = "SELECT columns FROM table;";
SqlCommand sqlCom = new SqlCommand(sqlText);
DataTable table = new DataTable();
SqlConnection linkToDB = DatabaseConnection();
sqlCom.Connection = linkToDB;
linkToDB.Open();
using (linkToDB)
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCom))
{
    adapter.Fill(table);
}     
dataMyGridView.DataSource = table;

I have tried to add a DataGridViewComboBox to this as follows –

DataGridViewComboBoxColumn colBox = new DataGridViewComboBoxColumn();
colBox.DataSource = GetListOfValues();   
dataMyGridView.Columns.Add(colbox);

Now this works, but it adds an entirely new column with the ComboBox, rather than converting one of the existing columns into a ComboBox.

Can anyone explain how I convert an existing Column in the dataMyGridView into a ComboBox?

The GetListOfValues function simply returns a DataTable containing all the possible values for the ComboBox field. It populates correctly, but like I said, its an entirely new column. How do I refer the added ComboBox to the relevant property in 'table'.

Best Answer

I answered a similar question today

Once a column is created you can't change its type. You can achieve your goal in two ways.

1.Create the required column, add it to the grid and bind the data. If you set the DataPropertyName property of your column then when your data is bound that data column will get bound to your grid column. The DataGridView will generate other columns automatically. Bind a second datasource to the comboboxcolumn itself.

2.Modify your database such that the list is provided by the database and binding will automatically create comboboxcolumn.

Related Topic