[英]Copy and Paste Selected Rows in an unbound DataGridView
我嘗試在 DataGridView 屬性中將 ClipboardCopyMode 更改為“EnableWithoutHeaderText”,但這不起作用。 另外,我嘗試使用下面的代碼以編程方式執行此操作,但它也不起作用。 請幫忙。
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
End Sub
您可以使用單元格值克隆選定的行,然后您可以使用InsertRange
插入副本單元格。 注意這種方式適用於未綁定的DataGridView
,如果您的DataGridView
已綁定,那么您應該復制控件的DataSource
的記錄。
C#
var insertAt = 0;
var rows = dataGridView1.SelectedRows.Cast<DataGridViewRow>()
.OrderBy(r=>r.Index)
.Select(r=>{
var clone = r.Clone() as DataGridViewRow;
for (int i = 0; i < r.Cells.Count; i++)
clone.Cells[i].Value= r.Cells[i].Value;
return clone;
}).ToArray();
dataGridView1.Rows.InsertRange(insertAt, rows);
VB
Dim insertAt = 0
Dim rows = DataGridView1.SelectedRows.Cast(Of DataGridViewRow) _
.OrderBy(Function(r) r.Index) _
.Select(Function(r)
Dim clone = DirectCast(r.Clone(), DataGridViewRow)
For i = 0 To r.Cells.Count - 1
clone.Cells(i).Value = r.Cells(i).Value
Next
Return clone
End Function) _
.ToArray()
DataGridView1.Rows.InsertRange(insertAt, rows)
筆記
DataGridView.Rows
集合也有InsertCopies
方法。 但是該方法只能復制連續范圍的行。 雖然上面的代碼也可以復制不連續的選擇。OrderBy(r=>r.Index)
以您在網格中看到的相同順序插入行,而不是選擇它們的順序。DataGridViewRow.Clone
方法克隆具有所有屬性但不具有單元格值的行,因此我使用 for 循環復制值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.