I'm showing a DataGridView on my VB.NET-GUI. In this table, the last row is a Total-Row which shows an average value.
Sorting after columns must actually be possible, but I'd like to fix the Total-Row somehow so it stays the last row. Is this possible or somehow a standard behavior?
It seems something like a TotalRow property doesn't exist.
It's possible for sure, by using a custom ordering function.
First, be sure all your columns have SortMode set to Automatic.
You need somehow to identify your TotalRow, so you can set its Tag property to string "Average":
row.Tag = "Average"
Then add this code:
Private Sub DataGridView1_SortCompare(sender As Object,
e As DataGridViewSortCompareEventArgs) Handles DataGridView1.SortCompare
If (DataGridView1.Rows(e.RowIndex1).Tag = "Average") Then
e.SortResult = If(DataGridView1.SortOrder = SortOrder.Ascending, 1, -1)
ElseIf (DataGridView1.Rows(e.RowIndex2).Tag = "Average") Then
e.SortResult = If(DataGridView1.SortOrder = SortOrder.Ascending, -1, 1)
Else
e.SortResult = System.String.Compare(e.CellValue1.ToString(),
e.CellValue2.ToString())
End If
e.Handled = True
End Sub
This will do the trick!
EDIT :
Since you talked about an average value, I assume you want to order elements by their numeric value, instead of ASCII-betically.
If you're sure that your DataGridView will only contain numbers, you can use a greater-than operator instead of the String.Compare in the last if branch:
e.SortResult = If(e.CellValue1 > e.CellValue2, 1, -1)
This way, your numbers will be ordered correctly (10, 20, 100, 200 rather than 10, 100, 20, 200).
If one needs to compare strings and numbers, I'd look for a Natural String Compare algorithm.
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