Procedimiento para permitir que los usuarios copien varias celdas en el Portapapeles desde el control DataGridView de formularios Windows Forms

Cuando se habilita la copia de celdas, los datos de su control DataGridView son más fácilmente accesibles para otras aplicaciones mediante el Clipboard. Los valores de las celdas seleccionadas se convierten en cadenas y se agregan al Portapapeles como valores de texto delimitados por tabulaciones para pegarlos en aplicaciones como el Bloc de notas y Excel, y como una tabla con formato HTML para pegarlos en aplicaciones como Word.

Puede configurar la copia de celdas para copiar solo valores de celda, para incluir el texto de encabezado de filas y columnas en los datos del Portapapeles, o para incluir el texto de encabezado solo cuando los usuarios seleccionan filas o columnas completas.

Según el modo de selección, los usuarios pueden seleccionar varios grupos de celdas desconectados. Cuando el usuario copia las celdas en el Portapapeles, no se copian las filas y columnas que no tienen celdas seleccionadas. Todas las demás filas o columnas se convierten en filas y columnas de la tabla de datos que se copia en el Portapapeles. Las celdas no seleccionadas en estas filas o columnas se copian como marcadores de posición en blanco en el Portapapeles.

Para habilitar la copia de celdas

  • Establecer la propiedad DataGridView.ClipboardCopyMode.

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

Ejemplo

En el ejemplo de código completo siguiente se muestra cómo se copian las celdas en el Portapapeles. Este ejemplo incluye un botón que copia las celdas seleccionadas en el Portapapeles usando el método DataGridView.GetClipboardContent y muestra el contenido del Portapapeles en un cuadro de texto.

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

Compilar el código

Este código requiere:

  • Referencias a los ensamblados N:System y N:System.Windows.Forms.

Consulte también