This is to move Datagridview Rows up,Down,Top and Bottom.
Here the main thing is, i binded value in datagridview using datatable.
Code:
Datagridview.Datasource=DataTable
Note:If the datagridview is binded in Row by Row method, its easy to move the Rows.
Follow the Steps.
1.Add a Datagridview and Four Buttons in a Form.
2.On Form_Load
Code:
'Bind a DataTable in Datagridview.
Button1.Text="Top"
Button2.Text="Up"
Button3.Text="Down"
Button4.Text="Bottom"
3.Create an Enum.
Code:
Enum mode
top = 0
up = 1
down = 2
bottom = 3
End Enum
5.Add the Below three Sub -->swapRows,toSelect,reshuffleRows
Code:
Private Sub swapRows(ByVal range As mode)
Dim iSelectedRow As Integer = -1
For iTmp As Integer = 0 To Datagridview.Rows.Count - 1
If Datagridview.Rows(iTmp).Selected Then
iSelectedRow = iTmp
Exit For
End If
Next
If iSelectedRow <> -1 Then
Dim sTmp(4) As String
For iTmp As Integer = 0 To Datagridview.Columns.Count - 1
sTmp(iTmp) = Datagridview.Rows(iSelectedRow).Cells(iTmp).Value.ToString
Next
Dim iNewRow As Integer
If range = mode.down Then
iNewRow = iSelectedRow + 1
ElseIf range = mode.up Then
iNewRow = iSelectedRow - 1
End If
If range = mode.up Or range = mode.down Then
For iTmp As Integer = 0 To Datagridview.Columns.Count - 1
Datagridview.Rows(iSelectedRow).Cells(iTmp).Value = Datagridview.Rows(iNewRow).Cells(iTmp).Value
Datagridview.Rows(iNewRow).Cells(iTmp).Value = sTmp(iTmp)
Next
toSelect(iNewRow)
ElseIf range = mode.top Or range = mode.bottom Then
reshuffleRows(sTmp, iSelectedRow, range)
End If
End If
End Sub
Private Sub toSelect(ByVal iNewRow As Integer)
Datagridview.Rows(iNewRow).Selected = True
End Sub
Private Sub reshuffleRows(ByVal sTmp() As String, ByVal iSelectedRow As Integer, ByVal Range As mode)
If Range = mode.top Then
Dim iFirstRow As Integer = 0
If iSelectedRow > iFirstRow Then
For iTmp As Integer = iSelectedRow To 1 Step -1
For iCol As Integer = 0 To Datagridview.Columns.Count - 1
Datagridview.Rows(iTmp).Cells(iCol).Value = Datagridview.Rows(iTmp - 1).Cells(iCol).Value
Next
Next
For iCol As Integer = 0 To Datagridview.Columns.Count - 1
Datagridview.Rows(iFirstRow).Cells(iCol).Value = sTmp(iCol).ToString
Next
toSelect(iFirstRow)
End If
Else
Dim iLastRow As Integer = Datagridview.Rows.Count - 1
If iSelectedRow < iLastRow Then
For iTmp As Integer = iSelectedRow To iLastRow - 1
For iCol As Integer = 0 To Datagridview.Columns.Count - 1
Datagridview.Rows(iTmp).Cells(iCol).Value = Datagridview.Rows(iTmp + 1).Cells(iCol).Value
Next
Next
For iCol As Integer = 0 To Datagridview.Columns.Count - 1
Datagridview.Rows(iLastRow).Cells(iCol).Value = sTmp(iCol).ToString
Next
toSelect(iLastRow)
End If
End If
End Sub
Finally, on the Button Click..
On Top Button Click
On Up Button Click
On Down Button Click
Code:
swapRows(mode.down)
On Bottom Button Click
Code:
swapRows(mode.bottom)

There might be lot of ways to do this.. if there anything simply to do this means, share with VBF..