Sorting a DataGridView by DataGridViewComboxBoxColumn
I want to be able to sort a DataGridView by the ComboBoxColumn so I can display groups based on the value in the ComboBoxColumn. When I click the ComboBoxColumn, the DataGridView does not respond unlike the other columns which are TextBoxColumns. Meaning, it do开发者_如何学编程es not sort when I click the column header.
How can I provide this feature or do I have to override the functionality of the column with my own custom class?
I just prototyped this very quickly, by adding an unbound DataGridView to a form, then adding four columns, two textbox columns and two combobox columns.
The entire code-behind is shown below:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn) dataGridView1.Columns[1];
DataGridViewComboBoxColumn col2 = (DataGridViewComboBoxColumn)dataGridView1.Columns[2];
List<string> items = new List<string>(){"B", "C", "E", "A"};
col.DataSource = items;
col.SortMode = DataGridViewColumnSortMode.Automatic;
col2.DataSource = items;
col2.SortMode = DataGridViewColumnSortMode.Automatic;
dataGridView1.Rows.Add(new string[] {"A", "B", "C", "D"});
dataGridView1.Rows.Add(new string[] { "B", "C", "C", "F" });
dataGridView1.Rows.Add(new string[] { "C", "B", "A", "A" });
}
}
The sorting is working perfectly for me in this very simple example.
You may need to post code examples to narrow down what the difference is in your code.
One possible I can think of is that I'm binding to a list of strings, not objects.
According to the documentation you can also provide your own custom handler for the SortCompare event.
Does this or this Url help at all??
Quote from the above Url:
The datagridview combobox column sorts on value of the column it is bound too. If you are using a datagridview to show the text representation of an id when you sort the column it will be on the id not the text.
I am sorting a DataGridViewComboBoxColumn by the value of the ComboBox text rather than the ID by, ordering the records in my ComboBox. I modified the source of the ComboBox to sort the records by the value displayed (ORDER BY [value_displayed] ASC/DESC) in SQL. This then means that the IDs of the records are in the same order as the values.
For example:
Un-sorted ComboBox: 1: Fernando, 2: Alex, 3: Charlie
Sorted ComboBox: 1: Alex, 2: Charlie, 3: Fernando
This means that, even though the DataGridView column sort is sorting based on the IDs, the text values are in the same order and therefore the column sort will be correct.
精彩评论