如何克隆和删除 DataGridView 中未选中的行?
How to clone and remove unselected rows in DataGridView?
我需要以编程方式删除 DataGridView 中除选定行之外的所有行。首先,我只需要从 CtrlDataGridView1 中获取选定的行并将它们放入 dgv。我试过这个
Public ReadOnly Property CtrlDataGridView1Filtered() As DataGridView
Get
Dim dgv As New DataGridView
dgv = CtrlDataGridView1
For Each dr As DataGridViewRow In CtrlDataGridView1.Rows
If Not dr.Selected Then
dgv.Rows.Remove(dr)
End If
Next
Return dgv
End Get
End Property
但是不行,因为CtrlDataGridView1的行被删除了。但我只需要删除 dgv 的行。
我该怎么办?如何解决这个问题?
您可以克隆 DataGridView,然后将所需的行复制到其中,例如
'CLONE COLUMNS ONLY'
Dim dgv As New DataGridView
For Each dgvCol As DataGridViewColumn In CtrlDataGridView1.Columns
dgv.Columns.Add(New DataGridViewColumn(dgvCol.CellTemplate))
Next
'COPY SELECTED / UNSELECTED ROWS AS PER YOUR REQUIREMENT'
For Each dr As DataGridViewRow In CtrlDataGridView1.Rows
If dr.Selected Then
'OR If Not dr.Selected Then'
dgv.Rows.Add(dr.Clone)
End If
Next
我需要以编程方式删除 DataGridView 中除选定行之外的所有行。首先,我只需要从 CtrlDataGridView1 中获取选定的行并将它们放入 dgv。我试过这个
Public ReadOnly Property CtrlDataGridView1Filtered() As DataGridView
Get
Dim dgv As New DataGridView
dgv = CtrlDataGridView1
For Each dr As DataGridViewRow In CtrlDataGridView1.Rows
If Not dr.Selected Then
dgv.Rows.Remove(dr)
End If
Next
Return dgv
End Get
End Property
但是不行,因为CtrlDataGridView1的行被删除了。但我只需要删除 dgv 的行。
我该怎么办?如何解决这个问题?
您可以克隆 DataGridView,然后将所需的行复制到其中,例如
'CLONE COLUMNS ONLY'
Dim dgv As New DataGridView
For Each dgvCol As DataGridViewColumn In CtrlDataGridView1.Columns
dgv.Columns.Add(New DataGridViewColumn(dgvCol.CellTemplate))
Next
'COPY SELECTED / UNSELECTED ROWS AS PER YOUR REQUIREMENT'
For Each dr As DataGridViewRow In CtrlDataGridView1.Rows
If dr.Selected Then
'OR If Not dr.Selected Then'
dgv.Rows.Add(dr.Clone)
End If
Next