vb.net DataGridView左移列和右移列连续移动进行排序,每行代码带注释
时间: 2024-03-22 21:38:01 浏览: 60
好的,以下是实现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
'循环遍历DataGridView的所有行,将当前选中列的值赋值给左侧列
For Each row As DataGridViewRow In dgvData.Rows
row.Cells(columnIndex - 1).Value = row.Cells(columnIndex).Value
row.Cells(columnIndex).Value = ""
Next
'将左移后的列设置为选中状态
dgvData.CurrentCell = dgvData.Rows(0).Cells(columnIndex - 1)
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
'循环遍历DataGridView的所有行,将当前选中列的值赋值给右侧列
For Each row As DataGridViewRow In dgvData.Rows
row.Cells(columnIndex + 1).Value = row.Cells(columnIndex).Value
row.Cells(columnIndex).Value = ""
Next
'将右移后的列设置为选中状态
dgvData.CurrentCell = dgvData.Rows(0).Cells(columnIndex + 1)
End Sub
Private Sub dgvData_ColumnDisplayIndexChanged(sender As Object, e As DataGridViewColumnEventArgs) Handles dgvData.ColumnDisplayIndexChanged
'获取当前移动的列
Dim movedColumn As DataGridViewColumn = e.Column
'循环遍历DataGridView的所有行,进行排序
For i As Integer = 0 To dgvData.Rows.Count - 2
'获取当前单元格的值
Dim currentValue As Object = dgvData.Rows(i).Cells(movedColumn.Index).Value
'获取下一个单元格的值
Dim nextValue As Object = dgvData.Rows(i + 1).Cells(movedColumn.Index).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的左移列和右移列,通过dgvData_ColumnDisplayIndexChanged事件实现连续移动进行排序。
阅读全文