简体   繁体   中英

DataGridView Copy a selected row issue

I have a datagridview and i want to copy the exact row that gets selected by the user to the same position (above). I have it right now so it inserts the line above the current line that is selected but it is not copying all the values. I'm just using a basic grid, no dataset or datatables. heres my code.

       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

The clone method only clones the row, not the data in it. You'll have to loop through the columns and add the values yourself after inserting it

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

The code is taken directly from the msdn link provided below

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

I updated your code to test if current row was not the first and to clone the cuurent row (not the first one).

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM