방법: 사용자가 Windows Forms DataGridView 컨트롤에서 여러 셀을 클립보드에 복사할 수 있도록 설정

셀 복사를 사용하면 DataGridView 컨트롤의 데이터가 Clipboard를 통해 다른 애플리케이션에 쉽게 액세스할 수 있습니다. 선택된 셀의 값은 문자열로 변환되고 메모장 및 Excel 같은 애플리케이션에 붙여넣도록 탭으로 구분된 텍스트 값으로 클립보드에 추가되거나 Word 같은 애플리케이션에 붙여넣도록 HTML 형식 테이블로 클립보드에 추가됩니다.

셀 값만 복사하거나 클립보드 데이터에 행 및 열 머리글 텍스트를 포함하거나 사용자가 전체 행이나 열을 선택할 때만 머리글을 포함하도록 셀 복사를 구성할 수 있습니다.

선택 모드에 따라 사용자는 연결이 끊어진 셀 그룹 여러 개를 선택할 수 있습니다. 사용자가 셀을 클립보드에 복사할 때 셀이 선택되지 않은 행과 열은 복사되지 않습니다. 모든 다른 행 또는 열은 클립보드에 복사된 데이터 테이블의 행과 열이 됩니다. 이들 행이나 열에서 선택되지 않은 셀은 빈 자리 표시자로 클립보드에 복사됩니다.

셀 복사를 사용하도록 설정하려면 다음을 수행합니다.

  • DataGridView.ClipboardCopyMode 속성을 설정합니다.

    this.DataGridView1.ClipboardCopyMode =
        DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
    
    Me.DataGridView1.ClipboardCopyMode = _
        DataGridViewClipboardCopyMode.EnableWithoutHeaderText
    

예제

다음 전체 코드 예제에서는 셀을 클립보드에 복사하는 방법을 보여 줍니다. 이 예제는 DataGridView.GetClipboardContent 메서드를 사용하여 선택된 셀을 클립보드에 복사하는 단추를 포함하고 클립보드 내용을 텍스트 상자에 표시합니다.

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.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

코드 컴파일

이 코드에는 다음이 필요합니다.

  • N:System 및 N:System.Windows.Forms 어셈블리에 대한 참조

참고 항목