views:

344

answers:

2

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

A: 

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.

Jacob Seleznev
Thanks. I found the second part of your answer about 10 seconds ago, but how are you supposed to do custom sort if you use the DataSource property? That sounds like a bad (or lazy) design decision to me, but I guess I don't know the whole story...
DaveN59
A: 

When the DataGridView is databound, the datasource can be sorted too.

Some datasources have built in support for sorting. Your datasource implements IBindingList or IBindingListView sorting properties and methods to sort a datasource in various ways.

Jacob Seleznev
This would work, I'm sure. I ended up not having to sort the columns after all (I just didn't allow the columns to be sorted, and that was OK with the end user), so it's a non-issue at the moment. If it becomes an issue, this would be the way to do it.
DaveN59