如何使用vb.net对datagridview中的int列进行排序

时间:2016-04-05 08:34:36

标签: vb.net winforms sorting datagridview

我在datagridview中有一个列,最初数据类型是字符串,但是当我注意到它有排序问题时,例如1 10 2 27 3 4,我将数据类型更改为int。问题仍然存在。

我已经更新了数据库并配置了表但仍然没有运气。

我现在该怎么办?

1 个答案:

答案 0 :(得分:0)

试试这个:

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

'或

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