首页 文章

DataGridView复制选定的行问题

提问于
浏览
0

我有一个datagridview,我想将用户选择的确切行复制到相同的位置(上图) . 我现在就拥有它,所以它在所选的当前行上方插入行,但它不会复制所有值 . 我只是使用基本网格,没有数据集或数据表 . 继承我的代码 .

If dgvPcPrevMonth.SelectedRows.Count > 0 Then
        dgvPcPrevMonth.Rows.Insert(dgvPcPrevMonth.CurrentCell.RowIndex,  dgvPcPrevMonth.SelectedRows(0).Clone)
    Else
        MessageBox.Show("Select a row before you copy")
    End If

2 回答

  • 2

    克隆方法仅克隆行,而不克隆其中的数据 . 您必须循环遍历列并在插入后自己添加值

    Public Function CloneWithValues(ByVal row As DataGridViewRow) _
        As DataGridViewRow
    
        CloneWithValues = CType(row.Clone(), DataGridViewRow)
        For index As Int32 = 0 To row.Cells.Count - 1
            CloneWithValues.Cells(index).Value = row.Cells(index).Value
        Next 
    
    End Function
    

    代码直接来自下面提供的msdn链接

    https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

  • 0

    我更新了你的代码,以测试当前行是不是第一行并克隆cuurent行(不是第一行) .

    If ddgvPcPrevMonth.CurrentCell.RowIndex > 0 Then
        dgvPcPrevMonth.Rows.Insert(dgvPcPrevMonth.CurrentCell.RowIndex,  dgvPcPrevMonth.Rows(dgvPcPrevMonth.CurrentCell.RowIndex-1).Clone)
     Else
        MessageBox.Show("Select a row (but not the first one) before you copy")
    End If
    

相关问题