Using VS2008, C# and .NET 3.5
I am using databound DataGridView controls to display tabular data read from a web service. In several cases, there is a numeric column that needs to be sorted. I have tried a couple of different ways to get this to work, but the column still ends up sorting alphabetically (ie, 1, 10, 2, 3 instead of 1, 2, 3, 10).
Setting the column data type to int doesn't work for databound controls, so the only real way to do this is to provide some custom sort logic.
Many people have suggested hooking in to the SortCompare event to provide custom sort logic, but for some reason the event code never runs -- I can put a breakpoint in the handler and it never gets there. I am adding the event handler through the GUI, so the handler is added to the control by VS, not manually.
Here's the event handler code, lifted from somewhere around here:
private void uxLicensedSoftwareDataGridView_SortCompare( object sender,
DataGridViewSortCompareEventArgs e )
{
int intValue1, intValue2;
if ( !Int32.TryParse( e.CellValue1.ToString(), out intValue1 ) )
return;
if ( !Int32.TryParse( e.CellValue2.ToString(), out intValue2 ) )
return;
if ( intValue1 == intValue2 )
e.SortResult = 0;
else if ( intValue1 < intValue2 )
e.SortResult = -1;
else
e.SortResult = 1;
e.Handled = true;
}
If this ever fired, it would do exactly what I want it to do. What could I be missing?
Thanks for pointing out the (hopefully) obvious... Dave
Set the sort mode of each column to "Automatic" rather than "Programmatic"
Also from this document:
The SortCompare event does not occur when the DataSource property is set or when the VirtualMode property value is true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With