绑定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
相关产品推荐
相关产品推荐

