vb.net DataGridView左移和右移进行排序,每行代码带注释
时间: 2024-03-22 22:38:04 浏览: 60
可排序,拖拽的GridView
好的,以下是实现DataGridView左移和右移进行排序的VB.NET代码,每行都有注释说明:
```
Private Sub btnLeft_Click(sender As Object, e As EventArgs) Handles btnLeft.Click
'获取当前选中的列
Dim selectedColumn As DataGridViewColumn = dgvData.Columns(dgvData.CurrentCell.ColumnIndex)
'获取当前选中列的索引
Dim columnIndex As Integer = selectedColumn.Index
'如果当前选中列是第一列,则不能左移
If columnIndex = 0 Then
Return
End If
'将当前选中列的DisplayIndex减1,实现左移
selectedColumn.DisplayIndex -= 1
'将左移后的列设置为选中状态
dgvData.CurrentCell = dgvData.Rows(0).Cells(columnIndex - 1)
'循环遍历DataGridView的所有行,进行排序
For i As Integer = 0 To dgvData.Rows.Count - 2
'获取当前单元格的值
Dim currentValue As Object = dgvData.Rows(i).Cells(columnIndex - 1).Value
'获取下一个单元格的值
Dim nextValue As Object = dgvData.Rows(i + 1).Cells(columnIndex - 1).Value
'如果当前单元格和下一个单元格的值都为空,则跳过本次循环
If currentValue Is Nothing AndAlso nextValue Is Nothing Then
Continue For
End If
'如果当前单元格的值为空,则将下一个单元格插入到当前单元格的前面
If currentValue Is Nothing Then
dgvData.Rows.RemoveAt(i + 1)
dgvData.Rows.Insert(i, dgvData.Rows(i + 1))
Continue For
End If
'如果下一个单元格的值为空,则将当前单元格插入到下一个单元格的前面
If nextValue Is Nothing Then
dgvData.Rows.RemoveAt(i)
dgvData.Rows.Insert(i + 1, dgvData.Rows(i))
Continue For
End If
'如果当前单元格的值小于下一个单元格的值,则将下一个单元格插入到当前单元格的前面
If currentValue.CompareTo(nextValue) > 0 Then
dgvData.Rows.RemoveAt(i + 1)
dgvData.Rows.Insert(i, dgvData.Rows(i + 1))
i -= 1
End If
Next
End Sub
Private Sub btnRight_Click(sender As Object, e As EventArgs) Handles btnRight.Click
'获取当前选中的列
Dim selectedColumn As DataGridViewColumn = dgvData.Columns(dgvData.CurrentCell.ColumnIndex)
'获取当前选中列的索引
Dim columnIndex As Integer = selectedColumn.Index
'如果当前选中列是最后一列,则不能右移
If columnIndex = dgvData.ColumnCount - 1 Then
Return
End If
'将当前选中列的DisplayIndex加1,实现右移
selectedColumn.DisplayIndex += 1
'将右移后的列设置为选中状态
dgvData.CurrentCell = dgvData.Rows(0).Cells(columnIndex + 1)
'循环遍历DataGridView的所有行,进行排序
For i As Integer = 0 To dgvData.Rows.Count - 2
'获取当前单元格的值
Dim currentValue As Object = dgvData.Rows(i).Cells(columnIndex + 1).Value
'获取下一个单元格的值
Dim nextValue As Object = dgvData.Rows(i + 1).Cells(columnIndex + 1).Value
'如果当前单元格和下一个单元格的值都为空,则跳过本次循环
If currentValue Is Nothing AndAlso nextValue Is Nothing Then
Continue For
End If
'如果当前单元格的值为空,则将下一个单元格插入到当前单元格的前面
If currentValue Is Nothing Then
dgvData.Rows.RemoveAt(i + 1)
dgvData.Rows.Insert(i, dgvData.Rows(i + 1))
Continue For
End If
'如果下一个单元格的值为空,则将当前单元格插入到下一个单元格的前面
If nextValue Is Nothing Then
dgvData.Rows.RemoveAt(i)
dgvData.Rows.Insert(i + 1, dgvData.Rows(i))
Continue For
End If
'如果当前单元格的值小于下一个单元格的值,则将下一个单元格插入到当前单元格的前面
If currentValue.CompareTo(nextValue) > 0 Then
dgvData.Rows.RemoveAt(i + 1)
dgvData.Rows.Insert(i, dgvData.Rows(i + 1))
i -= 1
End If
Next
End Sub
```
这段代码通过btnLeft和btnRight两个按钮实现DataGridView的左移列和右移列,通过循环遍历DataGridView的所有行进行排序。
阅读全文