vb.net DataGridView左移和右移,连续移动进行排序,每行代码带注释
时间: 2024-03-22 08:37:54 浏览: 108
好的,以下是实现DataGridView左移和右移,连续移动进行排序的VB.NET代码,每行都有注释说明:
```
Private Sub btnLeft_Click(sender As Object, e As EventArgs) Handles btnLeft.Click
'获取当前选中的单元格
Dim selectedCell As DataGridViewCell = dgvData.SelectedCells(0)
'获取当前选中单元格的列索引
Dim columnIndex As Integer = selectedCell.ColumnIndex
'如果当前选中单元格是第一列,则不能左移
If columnIndex = 0 Then
Return
End If
'获取当前选中单元格所在的行
Dim selectedRow As DataGridViewRow = dgvData.Rows(selectedCell.RowIndex)
'获取当前选中单元格的值
Dim selectedValue As Object = selectedRow.Cells(columnIndex).Value
'将当前选中单元格的值赋值给左侧单元格
dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex - 1).Value = selectedValue
'将左侧单元格的值赋值给当前选中单元格
dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex).Value = dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex - 1).Value
'清除当前选中单元格的值
dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex - 1).Value = ""
'将左移后的单元格设置为选中状态
dgvData.CurrentCell = dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex - 1)
End Sub
Private Sub btnRight_Click(sender As Object, e As EventArgs) Handles btnRight.Click
'获取当前选中的单元格
Dim selectedCell As DataGridViewCell = dgvData.SelectedCells(0)
'获取当前选中单元格的列索引
Dim columnIndex As Integer = selectedCell.ColumnIndex
'如果当前选中单元格是最后一列,则不能右移
If columnIndex = dgvData.ColumnCount - 1 Then
Return
End If
'获取当前选中单元格所在的行
Dim selectedRow As DataGridViewRow = dgvData.Rows(selectedCell.RowIndex)
'获取当前选中单元格的值
Dim selectedValue As Object = selectedRow.Cells(columnIndex).Value
'将当前选中单元格的值赋值给右侧单元格
dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex + 1).Value = selectedValue
'将右侧单元格的值赋值给当前选中单元格
dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex).Value = dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex + 1).Value
'清除当前选中单元格的值
dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex + 1).Value = ""
'将右移后的单元格设置为选中状态
dgvData.CurrentCell = dgvData.Rows(selectedCell.RowIndex).Cells(columnIndex + 1)
End Sub
Private Sub dgvData_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvData.CellValueChanged
'获取当前修改的单元格
Dim modifiedCell As DataGridViewCell = dgvData.Rows(e.RowIndex).Cells(e.ColumnIndex)
'获取当前修改单元格的值
Dim modifiedValue As Object = modifiedCell.Value
'循环遍历当前列的所有单元格,进行排序
For i As Integer = 0 To dgvData.Rows.Count - 1
'获取当前单元格的值
Dim currentValue As Object = dgvData.Rows(i).Cells(e.ColumnIndex).Value
'如果当前单元格的值为空,则跳过本次循环
If currentValue Is Nothing Then
Continue For
End If
'如果当前单元格的值小于修改单元格的值,则将修改单元格插入到当前单元格的前面
If currentValue.CompareTo(modifiedValue) > 0 Then
dgvData.Rows.RemoveAt(e.RowIndex)
dgvData.Rows.Insert(i, modifiedCell.OwningRow)
Exit For
End If
Next
End Sub
```
这段代码通过btnLeft和btnRight两个按钮实现DataGridView的左移和右移,通过dgvData_CellValueChanged事件实现连续移动进行排序。
阅读全文