Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView SortCompare event doesn't fire

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

like image 253
DaveN59 Avatar asked Sep 01 '09 15:09

DaveN59


1 Answers

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.

like image 100
Jacob Seleznev Avatar answered Sep 20 '22 12:09

Jacob Seleznev