简体   繁体   中英

How to sort int column in datagridview using vb.net

I have a column in datagridview which initially the data type is string, but when I notice that it has sorting problems like 1 10 2 27 3 4, I've change the data type to int. Bu the problem still remains.

I've updated the database and configured the table but still no luck.

What should I do now?

Try this:

Public Class Form1
 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

   'Creating test table
    Dim dt As New DataTable
    dt.Columns.Add("string")
    For i As Integer = 0 To 100
        dt.Rows.Add(dt.NewRow)
        dt.Rows(i)(0) = i.ToString
    Next

    'Sample
    dt.Columns.Add("integer", _
                GetType(System.Int32), "string")
    dt.DefaultView.Sort = "integer"
    dt.Columns("integer").ColumnMapping = _
             MappingType.Hidden
    DataGridView1.DataSource = dt
End Sub
End Class

'or

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    Dim r As New Random
    For i As Integer = 0 To 99
        Me.DataGridView1.Rows.Add(r.Next(1, 99).ToString, r.Next(1, 99).ToString, r.Next(1, 99).ToString)
    Next

    ' this adds a new column of type Integer
    Me.DataGridView1.Columns.Add("Dummy", "Dummy")
    Me.DataGridView1.Columns("Dummy").ValueType = GetType(Integer)
    ' hide the new column
    Me.DataGridView1.Columns("Dummy").Visible = False

    ' copy the original column values (here I use column 2)
    ' as Integers into new column
    For Each row As DataGridViewRow In Me.DataGridView1.Rows
        With row
            Dim v As Integer = 0
            If Integer.TryParse(.Cells(2).Value.ToString, v) Then
                .Cells("Dummy").Value = v
            End If
        End With
    Next
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    ' sort DataGridView on column ("Dummy") which indirectly sorts on 
    ' original column(2) - Descending
    Me.DataGridView1.Sort(Me.DataGridView1.Columns("Dummy"), System.ComponentModel.ListSortDirection.Descending)
End Sub

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