Clipboard Operations in WPF DataGrid (SfDataGrid)

12 Sep 202324 minutes to read

WPF DataGrid (SfDataGrid) provide support for the clipboard operations such as cut, copy and paste the data within control and between other applications such as Notepad, Excel. Clipboard operations copy and paste is enabled by default. You can copy selected records/cells from SfDataGrid by pressing Ctrl+C and also can paste the content from Clipboard to SfDataGrid by pressing Ctrl+V.

NOTE

Clipboard operations is not supported for the summary rows, add new row and unbound rows.

Copy to Clipboard in DataGrid

Copy operation works based on GridCopyOption property.

GridCopyOption provides the following options,

You have to use IncludeHeaders, IncludeFormat, IncludeHiddenColumn options along with CopyData option.

<syncfusion:SfDataGrid x:Name="dataGrid"
                       SelectionUnit="Row"
                       SelectionMode="Single"
                       GridCopyOption="CopyData,IncludeHeaders" 
                       ItemsSource="{Binding Orders}"/>
this.dataGrid.GridCopyOption = GridCopyOption.CopyData | GridCopyOption.IncludeHeaders;

Copy to Clipboard in WPF DataGrid

NOTE

IncludeHiddenColumn is not supported when SelectionUnit is Cell.

Paste from Clipboard in DataGrid

Paste operation works based on GridPasteOption property.

GridPasteOption provides the following options,

  • None – Disable paste in SfDataGrid.

  • PasteData – Enabled paste in SfDataGrid and when an incompatible value is pasted into a record/cell, the pasting operation is skipped for that particular record/cell.

  • ExcludeFirstLine – This can be used when pasting data copied with IncludeHeader copy option.

  • IncludeHiddenColumn – Paste the values in hidden columns also.

You have to use ExcludeFirstLine, IncludeHiddenColumn options along with PasteData option.

<syncfusion:SfDataGrid x:Name="dataGrid"
                       SelectionUnit="Row"
                       SelectionMode="Single"
                       GridPasteOption="PasteData,ExcludeFirstLine" 
                       ItemsSource="{Binding Orders}"/>
this.dataGrid.GridPasteOption = GridPasteOption.PasteData | GridPasteOption.ExcludeFirstLine;

Paste Clipboard Content in WPF DataGrid

Cut to Clipboard in DataGrid

Cut operation works based on GridCopyOption property.

GridCopyOption provides the following options,

You have to use IncludeHeaders, IncludeFormat, IncludeHiddenColumn options along with CutData option.

<syncfusion:SfDataGrid x:Name="dataGrid"
                       SelectionUnit="Row"
                       SelectionMode="Single"
                       GridCopyOption="CutData,IncludeHeaders" 
                       ItemsSource="{Binding Orders}"/>
this.dataGrid.GridCopyOption = GridCopyOption.CutData | GridCopyOption.IncludeHeaders;

Cut to Clipboard in WPF DataGrid

NOTE

IncludeHiddenColumn is not supported when SelectionUnit is Cell.

Events

GridCopyContent

GridCopyContent event occurs when copy/cut the cells in SfDataGrid. GridCopyPasteEventArgs provides information for GridCopyContent event. You can cancel copy operation by handling this event.

this.dataGrid.GridCopyContent += dataGrid_GridCopyContent;

void dataGrid_GridCopyContent(object sender, GridCopyPasteEventArgs e)
{

    if (((e.OriginalSender as SfDataGrid).SelectedItem as OrderInfo).OrderID == 1004)
        e.Handled = true;
}

GridPasteContent

GridPasteContent event occurs when paste the clipboard value into SfDataGrid. GridCopyPasteEventArgs provides information for GridPasteContent event. You can cancel paste operation by handling this event.

this.dataGrid.GridPasteContent+=dataGrid_GridPasteContent;

void dataGrid_GridPasteContent(object sender, GridCopyPasteEventArgs e)
{

    if (((e.OriginalSender as SfDataGrid).SelectedItem as OrderInfo).OrderID == 1010)
        e.Handled = true;
}

CopyGridCellContent

CopyGridCellContent event occurs when cell being copy/cut. GridCopyPasteCellEventArgs provides information for CopyGridCellContent event, which has following members,

You can change the text copied to clipboard by changing the ClipBoardValue.

this.dataGrid.CopyGridCellContent += dataGrid_CopyGridCellContent;

void dataGrid_CopyGridCellContent(object sender, GridCopyPasteCellEventArgs e)
{
}

The below code example change the clipboard value as 100 instead of cell value 1003 in SfDataGrid.

void dataGrid_CopyGridCellContent(object sender, GridCopyPasteCellEventArgs e)
{

    if (e.Column.MappingName == "OrderID" && (e.RowData as OrderInfo).OrderID == 1003)
        e.ClipBoardValue = 100;
}

Copy to Clipboard based on Cell Value in WPF DataGrid

The below code example handled the copy operation when MappingName of a Column is Country.

void dataGrid_CopyGridCellContent(object sender, GridCopyPasteCellEventArgs e)
{

    if (e.Column.MappingName == "Country")
        e.Handled = true;
}

Copy to Clipboard based on Mapping Name in WPF DataGrid

PasteGridCellContent

PasteGridCellContent event occurs when cell being paste. GridCopyPasteCellEventArgs provides information for PasteGridCellContent event, which has following members.

  • ClipBoardValue - Returns clipboard value of a particular cell.

  • Column – Returns corresponding GridColumn of a cell.

  • RowData – Returns corresponding RowData of a cell.

  • OriginalSender – Returns the SfDataGrid.

You can change the text paste to SfDataGrid by changing the ClipBoardValue.

this.dataGrid.PasteGridCellContent += dataGrid_PasteGridCellContent;

void dataGrid_PasteGridCellContent(object sender, GridCopyPasteCellEventArgs e)
{
}

The below code example change the clipboard value as Test instead of clipboard value BOLID.

void dataGrid_PasteGridCellContent(object sender, GridCopyPasteCellEventArgs e)
{

    if (e.Column.MappingName == "CustomerID" && (e.RowData as OrderInfo).CustomerID == "BERGS")
        e.ClipBoardValue = "Test";
}

Paste Clipboard Content based on Cell Value in WPF DataGrid

The below code example handled the paste operation when MappingName of Column is OrderID

void dataGrid_PasteGridCellContent(object sender, GridCopyPasteCellEventArgs e)
{

    if (e.Column.MappingName == "OrderID")
        e.Handled = true;
}

Paste Clipboard Content based on Mapping Name in WPF DataGrid

Handling Programmatically

Programmatically Copy to Clipboard in WPF DataGrid

Copy the selected records/cells in SfDataGrid by using Copy method in GridCopyPaste of SfDataGrid.

this.dataGrid.GridCopyPaste.Copy();

Copy a record by selecting the record using MoveCurrentCell method and Copy method in GridCopyPaste of SfDataGrid.

RowColumnIndex rowColumnIndex = new RowColumnIndex();
rowColumnIndex.RowIndex = 2;
rowColumnIndex.ColumnIndex = 2;
this.dataGrid.SelectionController.MoveCurrentCell(rowColumnIndex);
this.dataGrid.GridCopyPaste.Copy();

Copy the multiple records by selecting group of records using SelectRows method and Copy method in GridCopyPaste of SfDataGrid.

this.dataGrid.SelectionController.SelectRows(1, 7);
this.dataGrid.GridCopyPaste.Copy();

Copy the multiple cells by selecting group of cells using SelectCells method and Copy method in GridCopyPaste of SfDataGrid.

this.dataGrid.SelectCells(this.dataGrid.GetRowGenerator().Items[2].RowData, this.dataGrid.Columns[1], this.dataGrid.GetRowGenerator().Items[5].RowData, this.dataGrid.Columns[3]);
this.dataGrid.GridCopyPaste.Copy();

Copy rows without selecting in WPF DataGrid

You can copy the records without selection by using CopyRowsToClipboard method in GridCopyPaste of SfDataGrid.

this.dataGrid.GridCopyPaste.CopyRowsToClipboard(2, 4);

Programmatically Cut Data to Clipboard in WPF DataGrid

Cut the selected records/cells in SfDataGrid by using Cut method in GridCopyPaste of SfDataGrid.

this.dataGrid.GridCopyPaste.Cut();

Cut the entire record in SfDataGrid by selecting whole SfDataGrid using SelectAll method and Cut method in GridCopyPaste of SfDataGrid.

this.dataGrid.SelectionController.SelectAll();
this.dataGrid.GridCopyPaste.Cut();

Cut the entire column in SfDataGrid by using SelectCells method and Cut method in GridCopyPaste of SfDataGrid.

var firstRowData = this.dataGrid.GetRecordAtRowIndex(dataGrid.GetFirstRowIndex());
var lastRowData = this.dataGrid.GetRecordAtRowIndex(dataGrid.GetLastRowIndex());
this.dataGrid.SelectCells(firstRowData, this.dataGrid.Columns[2], lastRowData, this.dataGrid.Columns[2]);
this.dataGrid.GridCopyPaste.Cut();

Programmatically Paste in DataGrid

Paste the clipboard value into SfDataGrid by using Paste method in GridCopyPaste of SfDataGrid.

this.dataGrid.GridCopyPaste.Paste();

Paste the clipboard value into selected record by selecting the record using MoveCurrentCell method and Paste method in GridCopyPaste of SfDataGrid.

RowColumnIndex rowColumnIndex = new RowColumnIndex();
rowColumnIndex.RowIndex = 1;
rowColumnIndex.ColumnIndex = 1;
this.dataGrid.SelectionController.MoveCurrentCell(rowColumnIndex);
this.dataGrid.GridCopyPaste.Paste();

Customizing Copy Paste Behavior in WPF DataGrid

WPF DataGrid (SfDataGrid) process the clipboard operations in GridCutCopyPaste class. You can customize the default copy paste behaviors by overriding GridCutCopyPaste class and set it to SfDataGrid.GridCopyPaste.

public class CustomCopyPaste : GridCutCopyPaste
{

    public CustomCopyPaste(SfDataGrid sfGrid) : base(sfGrid)
    {        
    }
}
public MainWindow()
{
    InitializeComponent();
    this.dataGrid.GridCopyPaste = new CustomCopyPaste(this.dataGrid);
}

Paste a cell into many cells in WPF DataGrid

By default, you can copy one cell and paste it into another cell when Cell Selection is enabled in SfDataGrid. The below code shows how to copy one cell and paste it into all the selected cells by overriding PasteToCell method in GridCutCopyPaste class.

public class CustomCopyPaste : GridCutCopyPaste
{

    public CustomCopyPaste(SfDataGrid dataGrid) : base(dataGrid)
    {
    }

    protected override void PasteToCell(object record, GridColumn column, object value)
    {
        var text = Clipboard.GetText();
        
        string[] clipBoardText = Regex.Split(text, @"\r\n");
        
        clipBoardText = Regex.Split(clipBoardText[0], @"\t");

        //Get the clipBoardText and check if the clipBoardText is more than one cell

        //means call the base.

        if (clipBoardText.Count() > 1)
        {
            base.PasteToCell(record, column, value);
        }
        
        //Get the selectedCells for paste the copied cell 
        var selectedCells = this.dataGrid.GetSelectedCells();
        int selectedCellsCount = selectedCells.Count;
        
        for (int i = 0; i < selectedCellsCount; i++)
        {
            record = selectedCells[i].RowData;
            
            column = selectedCells[i].Column;
            
            //Call PasteToCell method with particular record of selectedCells,

            //Column of selected records and rowData

            if (record != null && column != null)
                base.PasteToCell(record, column, value);
        }
    }
}

Paste a record into many rows in WPF DataGrid

By default, you can able to copy one row and paste it into another row when Row Selection is enabled in SfDataGrid. The below code shows how to copy one row and paste it into all selected rows by overriding the PasteToRow method in the GridCutCopyPaste class.

public class CustomCopyPaste : GridCutCopyPaste
{

    public CustomCopyPaste(SfDataGrid dataGrid) : base(dataGrid)
    {
    }

    protected override void PasteToRow(object clipBoardContent, object selectedRecords)
    {
        var text = Clipboard.GetText();
        string[] clipBoardText = Regex.Split(text, @"\r\n");

        //Get the clipBoardText and check if the clipBoardText is more than one row

        //means call the base.

        if (clipBoardText.Count() > 1)
        {
            base.PasteToRow(clipBoardContent, selectedRecords);
            return;
        }

        var selectedRecord = this.dataGrid.SelectedItems;
        
        for (int i = 0; i < selectedRecord.Count; i++)
        {
            //Get the selected records for paste the copied row.
            selectedRecords = selectedRecord[i];
            
            //Call the PasteToRow method with clipBoardContent and selectedRecords
            base.PasteToRow(clipBoardContent, selectedRecords);
        }
    }
}

Select pasted records in WPF DataGrid

By default after pasting the clipboard value to SfDataGrid selection is maintains in previously selected records as it is. The below code shows select the pasted records after the Paste operation, by overriding the PasteToRows and PasteToRow methods in GridCutCopyPaste class. This code is applicable when SelectionUnit is Row.

public class CustomCopyPaste : GridCutCopyPaste
{

    public CustomCopyPaste(SfDataGrid dataGrid) : base(dataGrid)
    {
    }

    //Creating the new list for add the selected records
    public List<object> selectedItem = new List<object>();

    protected override void PasteToRows(object clipBoardRows)
    {
        base.PasteToRows(clipBoardRows);
        
        //Using the SelectionController apply the selection for Pasted records
        this.dataGrid.SelectionController.HandleGridOperations(new GridOperationsHandlerArgs(GridOperation.Paste, selectedItem));
    }

    protected override void PasteToRow(object clipBoardContent, object selectedRecords)
    {

        //Added the selected record to list
        selectedItem.Add(selectedRecords);
        
        base.PasteToRow(clipBoardContent, selectedRecords);
    }
}

Create new records while pasting in WPF DataGrid

By default while paste the clipboard value to SfDataGrid, it changes the values of the already existing records. The below code example shows how to add the copied records as new rows in SfDataGrid by overriding the PasteToRows method in GridCutCopyPaste class.

public class CustomCopyPaste : GridCutCopyPaste
{

    public CustomCopyPaste(SfDataGrid dataGrid)
        : base(dataGrid)
    {
    }
        
    protected override void PasteToRows(object clipBoardRows)
    {
        var copiedRecord = (string[])clipBoardRows;
        int copiedRecordsCount = copiedRecord.Count();

        //Based on the clipboard count added the new record for paste
 
        if (copiedRecordsCount > 0)
        {
            //Get the viewModel for adding the record
            var record = this.dataGrid.DataContext as ViewModel;
            
            for (int i = 0; i < copiedRecordsCount; i++)
            {
                //Create the new instance for Model, for adding the new record
                OrderInfo entity = new OrderInfo();
                
                for (int j = 0; j < this.dataGrid.Columns.Count; j++)
                {
                    string[] values = Regex.Split(copiedRecord[i], @"\t");

                    //Adding the new record by using PasteToCell method by passing the 
 
                    //created data, particular column, and clipboard value
                    this.PasteToCell(entity, this.dataGrid.Columns[j], values[j]);
                }
 
                //Added the pasted record in collection
                record.Orders.Add(entity);
            }
        }
    }
}

See Also

How to copy active cell value alone when SelectionUnit as Row

How to paste the copied row in AddNewRow?

How to paste the empty string while using Cell selection?

How to paste the data by custom column order instead of the first column in the SfDataGrid when SelectionUnit is a Row?

How to add the copied rows as new rows in the SfDataGrid while pasting?

How to copy one row and paste it into all the selected rows like Excel in the SfDataGrid?

How to copy one cell and paste it into all the selected cells in the SfDataGrid like the Excel?

How to copy the column and paste it as a new column by ContextMenu in SfDataGrid?