I want to develop an up/down row feature inside a binded datagridview (I found some examples but only with unbinded datagridview)
Here's my code:
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
Else
tblUpdatedDataSource = TryCast(MoveRowFromDataGridView(dtgHashtagDescripteurs, intSelectedRowIndex, "up"), Datatable)
End If
With dtgHashtagDescripteurs
.DataSource = Nothing
.Refresh()
.DataSource = tblUpdatedDataSource
.Refresh()
End With
End If
End Sub
Public Function MoveRowFromDataGridView(dgvToReorder As DataGridView, intSelectedRowIndex As Integer, strDirection As String) As DataTable
Dim tblSource As New DataTable
Dim rowToMove As DataRow
Dim rowCount As Integer
Dim rowsCollection As DataRowCollection
tblSource = TryCast(dgvToReorder.DataSource, DataTable)
If tblSource.Rows.Count > 0 Then
rowCount = tblSource.Rows.Count
rowsCollection = tblSource.Rows
If strDirection = "up" Then
rowToMove = rowsCollection(intSelectedRowIndex)
rowsCollection.Remove(rowToMove)
rowsCollection.InsertAt(rowToMove, intSelectedRowIndex - 1)
ElseIf strDirection = "down" Then
rowToMove = rowsCollection(intSelectedRowIndex)
rowsCollection.Remove(rowToMove)
rowsCollection.InsertAt(rowToMove, intSelectedRowIndex + 1)
End If
End If
Return tblSource
End Function
Several questions:
In debugging mode, when the app runs in
MoveRowFromDataGridView, tblSource got rows correctly sorted but got nothing once back MoveRowFromDataGridView.Updates to rowsCollection seems to pass on tblSource. Is there a way to prevent from that?
An other weird thing is the line
tblUpdatedDataSource = TryCast(MoveRowFromDataGridView(dtgHashtagDescripteurs, intSelectedRowIndex, "up"), Datatable)If I code like this:tblUpdatedDataSource = MoveRowFromDataGridView(dtgHashtagDescripteurs, intSelectedRowIndex, "up")I have an error "Option Strict On disallows implicit conversions from Datatable to Datatable"