将数据从Excel导入VisualBasic,我使用以下代码重新排序列:
Dim new_postion As Integer = dt_Excel.Columns.Count - 1
For i As Integer = 0 To dt_Excel.Columns.Count - 1
dt_Excel.Columns(i).SetOrdinal(new_postion)
new_postion = new_postion - 1
Next
DGV_Excel.DataSource = dt_Excel
但是当我在DataGridView中显示数据时,它仍然处于相同的顺序。
答案 0 :(得分:1)
将DataTable分配给DataGridView后,您尝试的操作将无法正常工作,至少不是以正确的方式。
在将DataTable分配给DataGridView.DataSource之前设置位置是最好的,但如果不可能,则使用DisplayIndex,例如DataGridView1.Columns(x).DisplayIndex = y
其中x是要更改的列索引,y也是我们将要更改的内容。
如果您在IDE中创建了DataGridView列,那么DisplayIndex是唯一可行的方法。
答案 1 :(得分:0)
答案 2 :(得分:0)
答案 3 :(得分:0)
按照您的评论从右到左排序的模拟示例
Module Module1
Sub Main()
Dim dt1 As New DataTable
dt1.Columns.Add(New DataColumn With {.ColumnName = "FirstName", .DataType = GetType(String)})
dt1.Columns.Add(New DataColumn With {.ColumnName = "MiddleName", .DataType = GetType(String)})
dt1.Columns.Add(New DataColumn With {.ColumnName = "LastName", .DataType = GetType(String)})
dt1.Rows.Add(New Object() {"Karen", "", "Payne"})
dt1.Rows.Add(New Object() {"Kevin", "S", "Gallagher"})
dt1.Rows.Add(New Object() {"Mary", "D", "Jones"})
Dim dt2 As New DataTable
dt2.Columns.Add(New DataColumn With {.ColumnName = "LastName", .DataType = GetType(String)})
dt2.Columns.Add(New DataColumn With {.ColumnName = "FirstName", .DataType = GetType(String)})
dt2.Columns.Add(New DataColumn With {.ColumnName = "MiddleName", .DataType = GetType(String)})
dt2.Rows.Add(New Object() {"Payne", "Karen", ""})
dt2.Rows.Add(New Object() {"Gallagher", "Kevin", "S"})
dt2.Rows.Add(New Object() {"Jones", "Mary", "D"})
Dim reverseList = dt1.Columns _
.Cast(Of DataColumn) _
.Select(
Function(column, index)
Return New With {.Position = index, .Name = column.ColumnName}
End Function) _
.OrderByDescending(Function(item) item.Position) _
.ToList
For Each item In reverseList
If dt2.Columns.Contains(item.Name) Then
dt2.Columns(item.Name).SetOrdinal(item.Position)
End If
Next
End Sub
End Module