2012-05-09 86 views
12

Tôi có một DataGridView trong ứng dụng .Net (V4 C# VS2010) & muốn sao chép tất cả dữ liệu vào khay nhớ tạm trên một lần bấm nút. Không có vấn đề -DataGridView: Sao chép hoàn thành vào clipboard

private void copyToClipboard() 
{ 
    dataGridView1.SelectAll(); 
    DataObject dataObj = dataGridView1.GetClipboardContent(); 
    if (dataObj != null) 
     Clipboard.SetDataObject(dataObj); 
} 

Vấn đề là người dùng có thể đã có một số tế bào, hàng vv lựa chọn trên DataGrid & Tôi không thực sự muốn thay đổi lựa chọn đó. Ở trên rõ ràng là chọn tất cả mọi thứ. Tôi có thể dataGridView1.ClearSelection(); ở cuối mà là tốt hơn nhưng vẫn không đạt được những gì cần thiết.

tôi có thể lưu các ô được chọn:

var mySelectedCells = dataGridView1.SelectedCells; 

nhưng làm thế nào để có được những ô được chọn chọn lại trên DataGrid sau khi copy? Có một cách dễ dàng để có được các bộ sưu tập các tế bào được lựa chọn trở lại vào DataGrid? Có lẽ có một cách tốt hơn để có được toàn bộ lưới được sao chép vào khay nhớ tạm ở nơi đầu tiên mà không ảnh hưởng đến các ô được chọn hiện tại?

Trả lời

10

Tôi cho rằng nếu bạn chỉ muốn thể hiện các nội dung của các tế bào dưới dạng văn bản và sao chép chúng vào clipboard, phân định theo tab, bạn có thể làm điều gì đó như:

var newline = System.Environment.NewLine; 
    var tab = "\t"; 
    var clipboard_string = ""; 

    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
     for (int i=0; i < row.Cells.Count; i++) 
     { 
       if(i == (row.Cells.Count - 1)) 
        clipboard_string += row.Cells[i].Value + newline; 
       else 
        clipboard_string += row.Cells[i].Value + tab; 
     } 
    } 

    Clipboard.SetText(clipboard_string); 

Sản lượng có vẻ khá giống với của GetClipboardContent(), nhưng hãy cẩn thận với bất kỳ DataGridViewImageColumns hoặc bất kỳ loại nào không phải là một chuỗi.

Chỉnh sửa: Anthony đúng, sử dụng StringBuilder để tránh phân bổ chuỗi mới cho mỗi lần ghép. Mã mới:

var newline = System.Environment.NewLine; 
    var tab = "\t"; 
    var clipboard_string = new StringBuilder(); 

    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
     for (int i = 0; i < row.Cells.Count; i++) 
     { 
      if (i == (row.Cells.Count - 1)) 
       clipboard_string.Append(row.Cells[i].Value + newline); 
      else 
       clipboard_string.Append(row.Cells[i].Value + tab); 
     } 
    } 

    Clipboard.SetText(clipboard_string.ToString()); 
+0

Cảm ơn. Đây là những gì tôi đã làm cuối cùng. Tôi đã phải thêm một câu lệnh if if (row.Cells [i] .Visible) 'bởi vì một vài cột là vô hình và giải pháp này sao chép tất cả các ô, có thể nhìn thấy hay không - (' dataGridView1.GetClipboardContent(); 'copy only công cụ hiển thị). Bạn không chắc chắn làm thế nào DataGridViewImageCell sẽ được xử lý nhưng đó không phải là một mối quan tâm cho ứng dụng cụ thể của tôi. – Nigel

+0

Không vấn đề gì Nigel, rất vui được giúp đỡ. Khi tôi đề cập đến DataGridViewImageCell, tôi chỉ có nghĩa là tôi không chắc chắn làm thế nào mã sẽ hành xử nếu bạn đang sử dụng bất cứ điều gì khác hơn là DataGridViewTextBoxCell, nhưng tôi tin rằng loại là mặc định nếu bạn không chỉ định khác. Nhưng nếu bạn đang sử dụng tất cả các ô TextBox, nó không phải là một vấn đề. Chúc mừng. –

+0

Chỉ muốn đề cập rằng nếu 'DataGridView' là lớn, bạn có thể muốn sử dụng một' StringBuilder' và không chỉ sử dụng chuỗi nối. – Anthony

0

Tôi nghĩ rằng phương pháp bên dưới chính xác sẽ làm những gì bạn muốn. Chỉ cần gọi phương thức này với tên DataGridView tại sự kiện nhấn nút.

Private Sub CopyDataGridViewToClipboard(ByRef dgv As DataGridView) 
    Try 
     Dim s As String = "" 
     Dim oCurrentCol As DataGridViewColumn 'Get header 
     oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible) 
     Do 
      s &= oCurrentCol.HeaderText & Chr(Keys.Tab) 
      oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, _ 
       DataGridViewElementStates.Visible, DataGridViewElementStates.None) 
     Loop Until oCurrentCol Is Nothing 
     s = s.Substring(0, s.Length - 1) 
     s &= Environment.NewLine 'Get rows 
     For Each row As DataGridViewRow In dgv.Rows 
      oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible) 
      Do 
       If row.Cells(oCurrentCol.Index).Value IsNot Nothing Then 
        s &= row.Cells(oCurrentCol.Index).Value.ToString 
       End If 
       s &= Chr(Keys.Tab) 
       oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, _ 
         DataGridViewElementStates.Visible, DataGridViewElementStates.None) 
      Loop Until oCurrentCol Is Nothing 
      s = s.Substring(0, s.Length - 1) 
      s &= Environment.NewLine 
     Next 'Put to clipboard 
     Dim o As New DataObject 
     o.SetText(s) 
     Clipboard.SetDataObject(o, True) 

    Catch ex As Exception 
     ShowError(ex, Me) 
    End Try 
End Sub 
1

Đây là phiên bản mã VB trong C# có tùy chọn sao chép tiêu đề và chỉ sao chép các hàng đã chọn.

private void CopyDataGridViewToClipboard(DataGridView dgv, bool includeHeaders = true, bool allRows = false) 
    { 
     // copies the contents of selected/all rows in a data grid view control to clipboard with optional headers 
     try 
     { 
      string s = ""; 
      DataGridViewColumn oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible); 
      if (includeHeaders) 
      {     
       do 
       { 
        s = s + oCurrentCol.HeaderText + "\t"; 
        oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None); 
       } 
       while (oCurrentCol != null); 
       s = s.Substring(0, s.Length - 1); 
       s = s + Environment.NewLine; //Get rows 
      } 
      foreach (DataGridViewRow row in dgv.Rows) 
      { 
       oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible); 

       if (row.Selected || allRows) 
       { 
        do 
        { 
         if (row.Cells[oCurrentCol.Index].Value != null) s = s + row.Cells[oCurrentCol.Index].Value.ToString(); 
         s = s + "\t"; 
         oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None); 
        } 
        while (oCurrentCol != null); 
        s = s.Substring(0, s.Length - 1); 
        s = s + Environment.NewLine; 
       }          
      } 
      Clipboard.SetText(s); 
     } 
     catch (Exception ex) 
     { 
      toolStripStatusLabel2.Text = @"Error: " + ex.Message; 
     } 
    } 
Các vấn đề liên quan