如何:使用户能够将多个单元格从 Windows 窗体 DataGridView 控件复制到剪贴板How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms DataGridView Control

启用单元格复制时,其他应用程序可以通过 Clipboard 轻松访问 DataGridView 控件中的数据。When you enable cell copying, you make the data in your DataGridView control easily accessible to other applications through the Clipboard. 将选定单元格的值转换为字符串,并作为制表符分隔的文本值添加到剪贴板以粘贴到记事本和 Excel 等应用程序中,或作为 HTML 格式的表格粘贴到 Word 等应用程序中。The values of the selected cells are converted to strings and added to the Clipboard as tab-delimited text values for pasting into applications like Notepad and Excel, and as an HTML-formatted table for pasting into applications like Word.

可以将单元复制格配置为:当用户选择整行或整列时,仅复制单元格的值、在剪贴板数据中包含行和列的标题文本,或仅包含标题文本。You can configure cell copying to copy cell values only, to include row and column header text in the Clipboard data, or to include header text only when users select entire rows or columns.

根据选择模式,用户可以选择多个不相连的单元格组。Depending on the selection mode, users can select multiple disconnected groups of cells. 用户将单元格复制到剪贴板时,不会复制不带选定单元格的行和列。When a user copies cells to the Clipboard, rows and columns with no selected cells are not copied. 所有其他行或列成为复制到剪贴板的数据表中的行和列。All other rows or columns become rows and columns in the table of data copied to the Clipboard. 将这些行或列中未选定的单元格作为空白占位符复制到剪贴板。Unselected cells in these rows or columns are copied as blank placeholders to the Clipboard.

启用单元格复制To enable cell copying

示例Example

下面的完整代码示例演示如何将单元格复制到剪贴板。The following complete code example demonstrates how cells are copied to the Clipboard. 此示例包含一个按钮,该按钮使用 DataGridView.GetClipboardContent 方法将选定的单元格复制到剪贴板,并在文本框中显示剪贴板内容。This example includes a button that copies the selected cells to the Clipboard using the DataGridView.GetClipboardContent method and displays the Clipboard contents in a text box.

using System;
using System.Windows.Forms;

public class Form1 : Form
{
    private DataGridView DataGridView1 = new DataGridView();
    private Button CopyPasteButton = new Button();
    private TextBox TextBox1 = new TextBox();

    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    public Form1()
    {
        this.DataGridView1.AllowUserToAddRows = false;
        this.DataGridView1.Dock = DockStyle.Fill;
        this.Controls.Add(this.DataGridView1);

        this.CopyPasteButton.Text = "copy/paste selected cells";
        this.CopyPasteButton.Dock = DockStyle.Top;
        this.CopyPasteButton.Click += new EventHandler(CopyPasteButton_Click);
        this.Controls.Add(this.CopyPasteButton);

        this.TextBox1.Multiline = true;
        this.TextBox1.Height = 100;
        this.TextBox1.Dock = DockStyle.Bottom;
        this.Controls.Add(this.TextBox1);

        this.Load += new EventHandler(Form1_Load);
        this.Text = "DataGridView Clipboard demo";
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {
        // Initialize the DataGridView control.
        this.DataGridView1.ColumnCount = 5;
        this.DataGridView1.Rows.Add(new string[] { "A", "B", "C", "D", "E" });
        this.DataGridView1.Rows.Add(new string[] { "F", "G", "H", "I", "J" });
        this.DataGridView1.Rows.Add(new string[] { "K", "L", "M", "N", "O" });
        this.DataGridView1.Rows.Add(new string[] { "P", "Q", "R", "S", "T" });
        this.DataGridView1.Rows.Add(new string[] { "U", "V", "W", "X", "Y" });
        this.DataGridView1.AutoResizeColumns();
        this.DataGridView1.ClipboardCopyMode = 
            DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
    }

    private void CopyPasteButton_Click(object sender, System.EventArgs e)
    {
        if (this.DataGridView1
            .GetCellCount(DataGridViewElementStates.Selected) > 0)
        {
            try
            {
                // Add the selection to the clipboard.
                Clipboard.SetDataObject(
                    this.DataGridView1.GetClipboardContent());
                
                // Replace the text box contents with the clipboard text.
                this.TextBox1.Text = Clipboard.GetText();
            }
            catch (System.Runtime.InteropServices.ExternalException)
            {
                this.TextBox1.Text = 
                    "The Clipboard could not be accessed. Please try again.";
            }
        }
    }

}
Imports System
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Private WithEvents DataGridView1 As New DataGridView()
    Private WithEvents CopyPasteButton As New Button()
    Private TextBox1 As New TextBox()

    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub

    Public Sub New()

        Me.DataGridView1.AllowUserToAddRows = False
        Me.DataGridView1.Dock = DockStyle.Fill
        Me.Controls.Add(Me.DataGridView1)

        Me.CopyPasteButton.Text = "copy/paste selected cells"
        Me.CopyPasteButton.Dock = DockStyle.Top
        Me.Controls.Add(Me.CopyPasteButton)

        Me.TextBox1.Multiline = True
        Me.TextBox1.Height = 100
        Me.TextBox1.Dock = DockStyle.Bottom
        Me.Controls.Add(Me.TextBox1)

        Me.Text = "DataGridView Clipboard demo"

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Me.Load

        ' Initialize the DataGridView control.
        Me.DataGridView1.ColumnCount = 5
        Me.DataGridView1.Rows.Add(New String() {"A", "B", "C", "D", "E"})
        Me.DataGridView1.Rows.Add(New String() {"F", "G", "H", "I", "J"})
        Me.DataGridView1.Rows.Add(New String() {"K", "L", "M", "N", "O"})
        Me.DataGridView1.Rows.Add(New String() {"P", "Q", "R", "S", "T"})
        Me.DataGridView1.Rows.Add(New String() {"U", "V", "W", "X", "Y"})
        Me.DataGridView1.AutoResizeColumns()
        Me.DataGridView1.ClipboardCopyMode = _
            DataGridViewClipboardCopyMode.EnableWithoutHeaderText

    End Sub

    Private Sub CopyPasteButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles CopyPasteButton.Click

        If Me.DataGridView1.GetCellCount( _
            DataGridViewElementStates.Selected) > 0 Then

            Try

                ' Add the selection to the clipboard.
                Clipboard.SetDataObject( _
                    Me.DataGridView1.GetClipboardContent())

                ' Replace the text box contents with the clipboard text.
                Me.TextBox1.Text = Clipboard.GetText()

            Catch ex As System.Runtime.InteropServices.ExternalException
                Me.TextBox1.Text = _
                    "The Clipboard could not be accessed. Please try again."
            End Try

        End If

    End Sub

End Class

编译代码Compiling the Code

此代码需要:This code requires:

  • 引用 N:System and N:System.Windows.Forms 程序集。References to the N:System and N:System.Windows.Forms assemblies.

请参阅See also