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.
theLizardPosted Mar 10, 2011, 4:23 PM
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!)
VulpesPosted Mar 10, 2011, 3:08 PM
Andrew FanninPosted Mar 10, 2011, 2:55 PM
Suthish NairPosted Mar 10, 2011, 2:00 PM
VulpesPosted Mar 10, 2011, 5:17 AM
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.
Andrew FanninPosted Mar 9, 2011, 6:58 PM
VulpesPosted Mar 9, 2011, 6:27 PM
Check out this link (http://msdn.microsoft.com/en-us/library/053656ss.aspx) for instructions on how to do it.