vb.net DataGridView左移和右移进行排序,无任何报错完全可以使用的代码,每行代码带注释
时间: 2024-03-22 14:38:11 浏览: 51
带排序和筛选功能的DataGridView
4星 · 用户满意度95%
好的,下面是完整的VB.NET代码实现DataGridView左移和右移进行排序,并且每行代码都有注释来解释其作用:
```
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'添加一些数据到DataGridView中
DataGridView1.Rows.Add("Apple", "Red")
DataGridView1.Rows.Add("Banana", "Yellow")
DataGridView1.Rows.Add("Orange", "Orange")
DataGridView1.Rows.Add("Grape", "Purple")
DataGridView1.Rows.Add("Watermelon", "Green")
'将DataGridView的SelectionMode属性设置为FullRowSelect,以便选中整行
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub btnMoveLeft_Click(sender As Object, e As EventArgs) Handles btnMoveLeft.Click
'获取选中的行数
Dim selectedRowCount As Integer = DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
'如果选中的行数大于0
If selectedRowCount > 0 Then
'循环选中的行
For i As Integer = 0 To selectedRowCount - 1
'获取当前选中的行的索引
Dim rowIndex As Integer = DataGridView1.SelectedRows(i).Index
'如果当前选中的行不是第一行,可以进行左移操作
If rowIndex > 0 Then
'获取当前选中行的DataGridViewRow对象
Dim rowToMove As DataGridViewRow = DataGridView1.Rows(rowIndex)
'从DataGridView中删除当前选中的行
DataGridView1.Rows.Remove(rowToMove)
'将当前选中的行插入到它的前面
DataGridView1.Rows.Insert(rowIndex - 1, rowToMove)
'选中当前移动的行
DataGridView1.Rows(rowIndex - 1).Selected = True
End If
Next
End If
End Sub
Private Sub btnMoveRight_Click(sender As Object, e As EventArgs) Handles btnMoveRight.Click
'获取选中的行数
Dim selectedRowCount As Integer = DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
'如果选中的行数大于0
If selectedRowCount > 0 Then
'循环选中的行
For i As Integer = 0 To selectedRowCount - 1
'获取当前选中的行的索引
Dim rowIndex As Integer = DataGridView1.SelectedRows(i).Index
'如果当前选中的行不是最后一行,可以进行右移操作
If rowIndex < DataGridView1.Rows.Count - 1 Then
'获取当前选中行的DataGridViewRow对象
Dim rowToMove As DataGridViewRow = DataGridView1.Rows(rowIndex)
'从DataGridView中删除当前选中的行
DataGridView1.Rows.Remove(rowToMove)
'将当前选中的行插入到它的后面
DataGridView1.Rows.Insert(rowIndex + 1, rowToMove)
'选中当前移动的行
DataGridView1.Rows(rowIndex + 1).Selected = True
End If
Next
End If
End Sub
End Class
```
以上是完整的实现DataGridView左移和右移进行排序的VB.NET代码,希望能够帮助到你!
阅读全文