在终止配置文件之前,我保存了Datagrid每列的显示索引。 重新启动应用程序时,我想在终止之前恢复列的顺序。 这不起作用。 这是我的重新排序代码:
Private Sub reorderColumns()
'convert the list of KeyValuePairs to a dictionary for easier access
Try
For Each column As DataGridViewColumn In MainDGV.Columns
column.DisplayIndex = SettingsKeeper.getInstance.positionOfColumnInGrid(column.Name)
Next
Catch ex As KeyNotFoundException
'Ignore, this means the config was not good, which generally means it was not yet
'created once
Catch ex As Exception
printErrorMessage(ex,ErrorCodes.Class_ReorderColumns)
End Try
End Sub
在我的初始化函数中,我遵循了这个post关于AutogenerateColumns属性的建议,但是没有解决任何问题。
这是我的defacto构造函数,需要在初始化后调用:
Public Sub init()
dt = New DataTable
Dim arr(CentralControl.dgvColumns.Count - 1) As String
Dim i As Integer = 0
For Each att As String In CentralControl.DataTemplate.Keys
dt.Columns.Add(att, GetType(String))
arr(i) = "No Data"
i += 1
Next
For i = 1 To SettingsKeeper.getInstance.numberRows
dt.Rows.Add(arr)
Next
MainDGV.AutoGenerateColumns = True
MainDGV.DataSource = dt
MainDGV.AutoGenerateColumns = False
reorderColumns()
End Sub
我的DataTemplate实际上是一个字典,其中包含datacolumn的名称作为键,以及一些用于计算此列的值作为字典条目值的规则。
答案 0 :(得分:0)
我将使用的解决方案,直到找到更清洁的东西: 稍微改变初始化函数:
Public Sub init()
dt = New DataTable
Dim arr(CentralControl.dgvColumns.Count - 1) As String
Dim i As Integer = 0
For Each att As String In CentralControl.DataTemplate.Keys
dt.Columns.Add(att, GetType(String))
arr(i) = "No Data"
i += 1
Next
For i = 1 To SettingsKeeper.getInstance.numberRows
dt.Rows.Add(arr)
Next
MainDGV.AutoGenerateColumns = False
MainDGV.DataSource = dt
'changes:
Dim sorted As New SortedDictionary(Of Integer, String)
For Each pair In SettingsKeeper.getInstance.positionOfColumnInGrid
sorted.Add(pair.Value, pair.Key)
Next
For Each col In sorted
Dim dgvcol As New DataGridViewTextBoxColumn
dgvcol.HeaderText = col.Value
dgvcol.Name = col.Value
dgvcol.DataPropertyName = col.Value
MainDGV.Columns.Add(dgvcol)
Next
end sub