VB.NET在SORTED数据表中向上/向下移动行

时间:2016-12-19 11:59:34

标签: vb.net sorting datagridview datatable

我正在尝试创建在datagridview中向上或向下移动的函数,这些函数来自datatable dtProc。在未绑定的datagridview上会很容易,但我试图用datasource = dtProc来实现它。问题是,我排序 dtProc指向RowNo(正确的顺序)。下面的功能有效,但只有ONCE。第二次它会移动原始位置的行,而不是所需的行,它们向上移动了1行。索引是正确的,但未排序的dtRows(在其上执行操作)具有不同的顺序,然后显示,排序dtRows。

Private Sub ShiftUp()
    If Me.dgwNew.SelectedRows.Count > 0 Then            ' if selection exists
        Dim selIdx As Int16 = Me.dgwNew.SelectedRows(0).Index      ' selected index
        Dim secIdx As Int16 = Me.dgwNew.SelectedRows(0).Index - 1  ' second index
        MsgBox("selIdx=" & selIdx & "     secIdx=" & secIdx)       ' test feedback
        dtProc.DefaultView.Sort = ("RowNo ASC")         ' trying to keep sorted order
        dtProc.Rows(selIdx)("RowNo") = secIdx + 1       ' swap selected index with second
        dtProc.Rows(secIdx)("RowNo") = selIdx + 1       ' swap second index with selected
        Call RefreshDgw()
        Me.dgwNew.ClearSelection()                      ' clear datagridview selection
        Me.dgwNew.CurrentCell = Me.dgwNew.Rows(secIdx).Cells(0)
        Me.dgwNew.Rows(secIdx).Selected = True          ' set selection on secondary row
    End If
End Sub

Private Sub RefreshDgw()
    dtProc.DefaultView.Sort = ("RowNo ASC")
    Me.dgwNew.DataSource = dtProc.DefaultView.ToTable
End Sub

有没有让它起作用的技巧?

编辑 - 最终解决方案:

我也无法使用DataView,问题仍然存在。所以我不得不添加一个额外的函数,它根据DataView中的行索引获取DataTable中的行索引。

Private Function GetDataTableRowID(rowIdx)
    Dim RetVal As Int16
    For ir = 0 To dtProc.Rows.Count - 1 
        If rowIdx + 1 = dtProc.Rows(ir)("RowNo") Then
            RetVal = ir
            Exit For
        End If
    Next
    Return RetVal
End Function

然后我修改了两行,我按如下方式设置索引:

        Dim selIdx As Int16 = Me.dgwNew.SelectedRows(0).Index      ' selected DataView index
        Dim secIdx As Int16 = Me.dgwNew.SelectedRows(0).Index - 1  ' second DataView index

        Dim selIdx2 As Int16 = GetDataTableRowID(selIdx)      ' selected DataTable index
        Dim secIdx2 As Int16 = GetDataTableRowID(secIdx)      ' second DataTable index

        dtProc.Rows(selIdx2)("RowNo") = secIdx + 1       ' swap selected index with second
        dtProc.Rows(secIdx2)("RowNo") = selIdx + 1       ' swap second index with selected

1 个答案:

答案 0 :(得分:0)

  1. 将一个Integer列添加到DataTable,名为Sequence
  2. 将表DefaultView.Sort设置为Sequence
  3. 创建一个DataView,最初对RowNo上的数据进行排序
  4. 迭代视图中的行,将序列分配给行索引
  5. 将您的表绑定到DataGridView
  6. 更改表格行中的序列值以上下移动行