简体   繁体   中英

How do I sort negative and positive values from a datagridview in vb.net?

I am relatively new to coding, and i was hoping someone could help me with sorting a column of negative and positive values in a datagridview. It is not connected to a datatable, as I am only reading the values from a textfile, that uses commas to separate each bits of data and display it in the datagridview. I have tried to use this code:

DGV.Sort(DGV.Columns(2), System.ComponentModel.ListSortDirection.descending)

However it only sorts according to the first integer of the value, and ignores the negative sign, so for example if the cells under that column had

3
-5
-2

It would sort so it would be

-5
3
-2

How can I sort so it takes the negative sign into account?

As it stands, the values in your grid are text, not numbers. As such, the grid is going sort them as text, not numbers. If you want the grid to sort them as numbers automatically then they have to actually be numbers.

You don't seem to be saying that you want standard numerical ordering though. You seem to be saying that what you want is to sort by the absolute value. That means the exact opposite of what you asked for, ie you want it to ignore the negative sign and sort by the number only. That will not happen automatically regardless of text or numbers.

In that case, you'll have to handle the SortCompare event of the grid. In the event handler, you can convert the text to numbers, take the absolute value and compare that yourself, eg

Dim num1 As Integer
Dim num2 As Integer

If Integer.TryParse(CStr(e.CellValue1), num1) AndAlso Integer.TryParse(CStr(e.CellValue2), num2) Then
    'Order the numbers based on their absolute value.
    e.SortResult = Math.Abs(num1).CompareTo(Math.Abs(num2))
Else
    'At least one of the values is not a number so consider them equivalent for sorting purposes.
    e.SortResult = 0
End If

e.Handled = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM