Set datagridview column to combobox.
I am working on a C# application that opens a table in a datagridview when a specific string is passed. I am trying to set certain columns' styles as comboboxes (Ex, datagridview.Columns[3] = ComboBox). I can not figure out the code to do this.

VulpesRank #55 · 29.2K reputationPosted Mar 9, 2011, 1:27 PM EST
Check out this link (http://msdn.microsoft.com/en-us/library/053656ss.aspx) for instructions on how to do it.
Andrew Fannin15 reputationPosted Mar 9, 2011, 1:58 PM EST
VulpesRank #55 · 29.2K reputationPosted Mar 10, 2011, 12:17 AM EST
int index = 3; // or whatever
// create new combobox column
DataGridViewComboBoxColumn newCol = new DataGridViewComboBoxColumn();
dataGridView1.Columns.Insert(index, newCol); // insert at the appropriate place
// copy over any properties from existing column now at index + 1
dataGridView1.Columns[index].HeaderText = dataGridView1.Columns[index + 1].HeaderText;
// copy other relevant properties
// remove existing column
dataGridView1.Columns.RemoveAt(index + 1);
You can't set dataGridView1.Columns[3] directly because it's read only.
Suthish NairRank #92 · 22.8K reputationPosted Mar 10, 2011, 9:00 AM EST
Andrew Fannin15 reputationPosted Mar 10, 2011, 9:55 AM EST
VulpesRank #55 · 29.2K reputationPosted Mar 10, 2011, 10:08 AM EST
theLizardRank #1,079 · 1.8K reputationPosted Mar 10, 2011, 11:23 AM EST
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
return;
string s = "SELECT field FROM table WHERE field = '" + dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() + ""';
//this is where you would load your combo box from another table
DataGridViewComboBoxCell newCb = new DataGridViewComboBoxCell();
//do your load loop here
// newCb.Items.Add(s);
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = newCb;
}
I have tested it manually, it replaces the current cell with a combo box cell and has the value of the original cell text in the items list.
There is always a way of doing things...
Edit: You could also do this when you load the grid from your database in your loop when adding rows (I assume you are doing this!)