Floc
Floc

Reputation: 698

Sort DataGridColumn with null values always at bottom

I want a column in my DataGrid to sort with null values always at end. I've tried to do this by following this (part 1) and this (part 2). But my custom sort doesn't work like I want.

Thats my compare method for my column :

private int NullableDateTimeCompare(DateTime? date1, DateTime? date2, int direction)
{
    if (date1.HasValue && date2.HasValue)
        return DateTime.Compare(date1.Value, date2.Value)*direction;
    if (!date1.HasValue && !date2.HasValue)
        return 0;
    if (date1.HasValue)
        return 1 * -direction; // Tried different things but nothing work like I will
    return -1 * -direction; // Tried different things but nothing work like I will
}

I've the impression that this doesn't work because DataGrid cached the Compare result and so inverse the sort when user sort (and don't run another time the Compare).

Have you an idea on how to do that ?

Thanks you !

Upvotes: 0

Views: 1401

Answers (2)

Floc
Floc

Reputation: 698

I was making a simple project to share with you to explain my issue. And I found the solution.

It's like @juharr answer but the reverse.

if (date1.HasValue)
    return -1;
return 1;

Don't know why it must be like that but it works. Nulls are always on bottom.

So thanks to @juharr !

Upvotes: 0

juharr
juharr

Reputation: 32296

As you code currently stands the following will return 1

NullableDateTimeCompare(DateTime.Now, null, -1);
NullableDateTimeCompare(null, DateTime.Now, 1);

And these will return -1

NullableDateTimeCompare(DateTime.Now, null, 1);
NullableDateTimeCompare(null, DateTime.Now, -1);

But what you want is for these to return 1

NullableDateTimeCompare(DateTime.Now, null, -1);
NullableDateTimeCompare(DateTime.Now, null, 1);

and these to return -1

NullableDateTimeCompare(null, DateTime.Now, 1);
NullableDateTimeCompare(null, DateTime.Now, -1);

To achieve that just return 1 or -1 at the end of the function

if (date1.HasValue)
    return 1;
return -1;

Upvotes: 1

Related Questions