[英]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. 我对编码比较陌生,我希望有人可以帮我在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. 它没有连接到数据表,因为我只读取文本文件中的值,它使用逗号分隔每个数据位并在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. 在这种情况下,您将必须处理网格的SortCompare
事件。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.