2016-04-05 103 views
0

我在datagridview中有一列,最初數據類型是字符串,但是當我注意到它具有排序問題(如1 10 2 27 3 4)時,我更改了數據類型爲int。問題仍然存在。如何使用vb.net在datagridview中對int列進行排序

我已更新數據庫並配置了表格,但仍然沒有運氣。

現在該怎麼辦?

回答

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 
+0

但我不會在我的代碼添加列..在我有一個數據源..對不起,我很差勁在解釋,但我想你會理解對嗎? –

+0

@ J.Leo用一個例子編輯你的問題.. – Dejan

+0

@ J.Leo你可以對數據視圖進行排序並綁定到網格 – Dejan

相關問題