您可以克隆,選擇行與細胞的值,那麼你可以使用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循環複製了值。
- 您可以根據上述代碼簡單地創建擴展方法。它會更可重用。
我不確定這可以幫助您或不需要訪問http://stackoverflow.com/questions/7750746/how-to-copy-one-row-to-another-row-in-gridview –
任何改進?只是爲了確保我不浪費時間:) – noidea
究竟是什麼要求?請添加關於您想要做什麼的描述,您期望的是什麼,並告訴我們您嘗試的代碼有什麼問題。 –