'vb.net - Sort datagridview column numerically

I know this has been asked quite a few times, but i'm having issues with the solutions found on most other pages.

I have a single datagridview column that i want to be sorted by number (1,2,10 instead of 1,10,2) Best i can see online, i need to convert the column or cell to an integer value type - but i'm not sure how to do so.

I've tried grid.columns(4).valuetype = typeof(System.int32), and tried the same for cells individually.

Trying above always results in a "int32 is a type in 'system' and cannot be used as an expression" error - which i'm not sure about.

The data itself is obtained froma text file, and converted from string to integer when being added into the cell datagrid_alltracks.Rows(shutupaboutlambda).Cells(4).Value = CInt(numstring))



Solution 1:[1]

You can just set the DataGridView SortCompare Event to compare two integers (or two singles, or two doubles). Code wise (calling your datagridview "grid")

Private Sub grid_SortCompare(sender as Object, e as DataGridViewSortCompareEventArgs) Handles grid.SortCompare
    e.SortResult = CInt(e.cellvalue1).CompareTo(CInt(e.cellValue2))
    e.Handled = True
End Sub

if you are doing single or double variables, use CSng or CDbl instead of CInt

    e.SortResult = CSng(e.cellvalue1).Compareto(CSng(e.CellValue2) 

You can do more fancy sorting if you want, You basically need to know that e.SortResult is Positive, Negative or Zero, and your cells are sorted according to that result (Positive keep order, negative reverse order, Zero - matched - do nothing (yet)). The current row index(s) and column are available in the e arguments so you can also compare adjacent column data if the current cells are matched)

Solution 2:[2]

I know I'm coming to the party late, but I found that I once I had added the data, I needed to convert the desired columns to have a data type.

I'm adding data like the following:

DataGridView1.Rows.Add(New String() {CInt(recordnum), True, "play", wszName.ToString, qiOffset.ToString, value.ToString, qiLength.ToString})

Then, after all the data has been added, I then do a simple loop and convert the column, where I can then sort it. It's set up so you can do multiple columns if need be.

Dim colnum As Integer
colnum = 0 ' set this as your column to change the data type to

For i As Integer = 0 To DataGridView1.Rows.Count - 1
    Dim d As Double = Double.Parse(DataGridView1.Rows(i).Cells(colnum).Value.ToString())
    DataGridView1.Rows(i).Cells(colnum).Value = CInt(d)
    DataGridView1.Rows(i).Cells(colnum).ValueType = GetType(Double)
Next

Sorting can work for whatever column you adjusted. In this case, it's column 4.

DataGridView1.Sort(DataGridView1.Columns(4), System.ComponentModel.ListSortDirection.Ascending)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Giorgio Barchiesi
Solution 2 vr_driver