DataGridView.SortCompare Event
Assembly: System.Windows.Forms (in system.windows.forms.dll)
This event occurs only when the DataSource property is not set and the VirtualMode property value is false.
This event compares pairs of cells in the column being sorted. It occurs only when the user clicks the header of a column with a SortMode property value of Automatic, or when you call the Sort(DataGridViewColumn,ListSortDirection) overload. When this event occurs for a column with a SortMode property value of Programmatic, you must display the sorting glyph yourself through the DataGridViewColumnHeaderCell.SortGlyphDirection property.
You can use this event to sort rows using the cell values in one column or in multiple columns. Use the CellValue1 and CellValue2 properties to compare cell values in the column specified in the Column property. Use the RowIndex1 and RowIndex2 properties to access values in other columns through the Rows collection.
For more information about handling events, see Consuming Events.
The following code example demonstrates how to use the SortCompare in a multiple column sort. This example is part of a larger example provided in How to: Customize Sorting in the Windows Forms DataGridView Control.
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { // 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.Column.Name != "ID") { e.SortResult = System.String.Compare( dataGridView1.Rows[e.RowIndex1].Cells["ID"].Value.ToString(), dataGridView1.Rows[e.RowIndex2].Cells["ID"].Value.ToString()); } e.Handled = true; }
Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.Reference
DataGridView ClassDataGridView Members
System.Windows.Forms Namespace
DataGridViewSortCompareEventHandler
DataGridViewSortCompareEventArgs
OnSortCompare
DataGridViewColumn.SortMode
DataGridViewColumnHeaderCell.SortGlyphDirection
Other Resources
DataGridView Control (Windows Forms)How to: Customize Sorting in the Windows Forms DataGridView Control