我需要以编程方式删除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的行。
我该怎么办?怎么解决这个问题?
答案 0 :(得分:1)
您可以克隆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