In the code below I've created the combobox in specific columns, and populated with elements on cell click event.
I've used a string list and string array to populate the combobox dropdown list which may be different to your requirements.
I haven't included this in the code, but on form load I use an external XML file to populate a datatable which then used as the datagridview source. I then have a save button which overwrites the original XML file by capturing the datagridview and saving it back to XML.
Using this method, when the row header is clicked to filter/change the order of the dgv, the cell combobox selection and dropdown list elements works fine.
Hopefully there is something there that will set you on the right path.
public partial class RuleWindow : Form
{
private object item;
private DataGridViewComboBoxCell combo;
//set item variable to combobox selection text upon selection
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cbx = (ComboBox)sender;
item = cbx.Text;
}
//add comboboxes to relevant columns. Populate with relevant elements
private void datagridview_CellClick(object sender, DataGridViewCellEventArgs e)
{
if ((e.ColumnIndex == datagridview.Columns[0].Index && e.RowIndex > -1) || (e.ColumnIndex == datagridview.Columns[1].Index && e.RowIndex > -1))
{
if (combo == null)
{
DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
//example of adding string array to comboBox
string[] operators = { ">", "<", "≤", "≥", "=" };
combo.Items.AddRange(operators);
this.datagridview[e.ColumnIndex, e.RowIndex] = combo;
}
}
else if (e.ColumnIndex == datagridview.Columns[2].Index && e.RowIndex > -1)
{
if (combo == null)
{
DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
//example of adding list to comboBox (uses external extension method not in this code - replace as required)
List<string> layerList = ExtensionMethods.SortedAcadLayerList();
combo.Items.AddRange(layerList.ToArray());
this.datagridview[e.ColumnIndex, e.RowIndex] = combo;
}
}
}
private void datagridview_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
private void datagridview_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if ((e.ColumnIndex == datagridview.Columns[0].Index && e.RowIndex > -1) ||
(e.ColumnIndex == datagridview.Columns[1].Index && e.RowIndex > -1) ||
(e.ColumnIndex == datagridview.Columns[2].Index && e.RowIndex > -1))
{
combo = null;
datagridview[e.ColumnIndex, e.RowIndex] = new DataGridViewTextBoxCell();
datagridview[e.ColumnIndex, e.RowIndex].Value = item;
}
}
}