You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绑定DataGridView中行上下移动功能开发问题求助

绑定DataGridView行上下移动问题解决方案

问题分析与修正

问题1:返回后无数据

核心原因是代码中TryCast使用了错误的类型名称Datatable(小写t),正确应为DataTable(大写T),导致转换失败,tblUpdatedDataSource变为Nothing,绑定后DataGridView无数据。同时重新绑定逻辑可以简化,无需先清空数据源。

问题2:操作同步到原表

rowsCollection是tblSource.Rows的直接引用,操作它必然会修改原表。解决办法是创建原DataTable的深拷贝,操作副本而非原表。

问题3:直接赋值报错

同样是类型名拼写错误(Datatable vs DataTable),Option Strict On要求严格类型匹配,修正拼写后直接赋值即可,无需TryCast。


修正后的完整代码

KeyUp事件处理

Private Sub dtgHashtagDescripteurs_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) Handles dtgHashtagDescripteurs.KeyUp
    Dim tblUpdatedDataSource As DataTable

    If e.KeyCode.Equals(Keys.Up) Then
        Dim intSelectedRowIndex As Integer = dtgHashtagDescripteurs.CurrentCell.RowIndex
        If intSelectedRowIndex = 0 Then Exit Sub
        
        ' 修正类型拼写,直接赋值
        tblUpdatedDataSource = MoveRowFromDataGridView(dtgHashtagDescripteurs, intSelectedRowIndex, "up")
        
        ' 重新绑定并重置选中行
        dtgHashtagDescripteurs.DataSource = tblUpdatedDataSource
        dtgHashtagDescripteurs.CurrentCell = dtgHashtagDescripteurs.Rows(intSelectedRowIndex - 1).Cells(0)
    ElseIf e.KeyCode.Equals(Keys.Down) Then
        Dim intSelectedRowIndex As Integer = dtgHashtagDescripteurs.CurrentCell.RowIndex
        If intSelectedRowIndex = dtgHashtagDescripteurs.Rows.Count - 1 Then Exit Sub
        
        tblUpdatedDataSource = MoveRowFromDataGridView(dtgHashtagDescripteurs, intSelectedRowIndex, "down")
        
        dtgHashtagDescripteurs.DataSource = tblUpdatedDataSource
        dtgHashtagDescripteurs.CurrentCell = dtgHashtagDescripteurs.Rows(intSelectedRowIndex + 1).Cells(0)
    End If
End Sub

行移动方法

Public Function MoveRowFromDataGridView(dgvToReorder As DataGridView, intSelectedRowIndex As Integer, strDirection As String) As DataTable
    Dim originalTable As DataTable = TryCast(dgvToReorder.DataSource, DataTable)
    If originalTable Is Nothing OrElse originalTable.Rows.Count = 0 Then
        Return originalTable
    End If
    
    ' 创建原表的深拷贝,避免修改原数据源
    Dim tblSource As DataTable = originalTable.Copy()
    Dim rowToMove As DataRow = tblSource.Rows(intSelectedRowIndex)
    
    Select Case strDirection
        Case "up"
            tblSource.Rows.Remove(rowToMove)
            tblSource.Rows.InsertAt(rowToMove, intSelectedRowIndex - 1)
        Case "down"
            tblSource.Rows.Remove(rowToMove)
            tblSource.Rows.InsertAt(rowToMove, intSelectedRowIndex + 1)
    End Select        
    Return tblSource
End Function

内容的提问来源于stack exchange,提问作者8oris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:55:14