2016-09-22 77 views
2

我試過在DataGridView屬性中將ClipboardCopyMode更改爲「EnableWithoutHeaderText」,但這不起作用。此外,我嘗試用下面的代碼以編程方式執行此操作,但它也不起作用。請幫忙。在未綁定的DataGridView中複製並粘貼選定的行

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick 
    Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText 
End Sub 
+0

我不確定這可以幫助您或不需要訪問http://stackoverflow.com/questions/7750746/how-to-copy-one-row-to-another-row-in-gridview –

+0

任何改進?只是爲了確保我不浪費時間:) – noidea

+0

究竟是什麼要求?請添加關於您想要做什麼的描述,您期望的是什麼,並告訴我們您嘗試的代碼有什麼問題。 –

回答

1

您可以克隆,選擇行與細胞的值,那麼你可以使用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循環複製了值。
  • 您可以根據上述代碼簡單地創建擴展方法。它會更可重用。