Sorting an unbound column
Hi,
I have a DataGridView bound to a bindingSource, it also contains an unbound calculated column. I have found that sorting isn't supported on the unbound column. Is there a way I can perform my own sorting for this particular column?
Thanks for your help
Graham
[270 byte] By [
Gravy] at [2008-2-19]
No - we do not support sorting an unbound column when there are other databound columns. The best you can do is to manually "sort" the values and your databound column values and set the column header's sort glyph to indicate that the column is sorted.
-mark
Program Manager
Microsoft
This post is provided "as-is"
Sorting on unbound columns is a do-it-yourself task. You have to handle the column header clicks, track the sort order (ascending/descending), indicate the sort order (via the SortGlyph) and depending on what you are after, even sort the underlying data.
Suppose you have a dataset with an employees table, and this table has a BirthDate column. You have an Age column that is unbound and calculated using BirthDate. You can handle clicks in the Age column header and fire a sort on the BirthDate column (in reverse order, of course). Firing a DataGridView.Sort() on an unbound column generates an error. Here is some sample code that may help you:
| |
private void employeesDataGridView_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { DataGridView dgv = sender as DataGridView; if (e.Column.Name == "Age") { // Try to sort based on the cells in the current column. e.SortResult = System. String.Compare( e.CellValue1.ToString(), e.CellValue2.ToString()); // If the cells are equal, sort based on the ID column. if (e.SortResult == 0) { e.SortResult = System. String.Compare( dgv.Rows[e.RowIndex1].Cells[ "BirthDate"].Value.ToString(), dgv.Rows[e.RowIndex2].Cells[ "BirthDate"].Value.ToString()); } e.Handled = true; } else { e.Handled = false; } } private void employeesDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { DataGridView dgv = sender as DataGridView; DataGridViewColumn col = dgv.Columns[e.ColumnIndex]; if (col.Name == "Age") { DataGridViewColumn colBirthDate = dgv.Columns["BirthDate"]; // You will need to track the current sort direction. This is hard-coded // to sort ascending only. dgv.Sort(colBirthDate, ListSortDirection.Descending); colBirthDate.HeaderCell.SortGlyphDirection = SortOrder.Descending; col.HeaderCell.SortGlyphDirection = SortOrder.Ascending; } } |
If you don't have another column you can sort on instead, then you can implement SortCompare or an IComparer interface that does some complicated sort logic, but still, you will have to have another column (or a dummy hidden column?) on which you fire the sort.
I tried to do what suggested, but the SortCompare event doesnt fired.
I am using datagridview in VirtualMode.
Does anyone has idea how to sort unbound column when VirtualMode set to true?
thanks,
Tomer