Category / Section
How to paste the empty string while using cell selection in WPF DataGrid (SfDataGrid)?
1 min read
The empty string will not be allowed to paste in GridCell when the SelectionUnit is Cell or Any in WPF DataGrid (SfDataGrid). But you can achieve this by overriding the PasteToRow method in GridCutCopyPaste class like below code.
C#
public class CustomCopyPaste : GridCutCopyPaste { public CustomCopyPaste(SfDataGrid sfgrid) : base(sfgrid) { } protected override void PasteToRow(object clipboardcontent, object selectedRecords) { if (dataGrid.SelectionUnit == GridSelectionUnit.Row) base.PasteToRow(clipboardcontent, selectedRecords); else { //Get the copied value. clipboardcontent = Regex.Split(clipboardcontent.ToString(), @"\t"); var copyValue = (string[])clipboardcontent; int cellcount = copyValue.Count(); var selectionContoller = this.dataGrid.SelectionController as GridCellSelectionController; var lastselectedindex = selectionContoller.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex; //Get the PressedRowColumnIndex value using reflection from SelectionController. var PropertyInfo = (this.dataGrid.SelectionController as GridCellSelectionController).GetType().GetProperty("PressedRowColumnIndex", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var pressedrowcolumnindex = PropertyInfo.GetValue(this.dataGrid.SelectionController); var pressedindex = ((RowColumnIndex)(pressedrowcolumnindex)).ColumnIndex; //Get the column index value that want to paste the first value. var pastecolumnindex = pressedindex < lastselectedindex ? pressedindex : lastselectedindex; int columnindex = 0; var columnStartIndex = this.dataGrid.ResolveToGridVisibleColumnIndex(pastecolumnindex); for (int i = columnStartIndex; i < cellcount + columnStartIndex; i++) { if (dataGrid.GridPasteOption.HasFlag(GridPasteOption.IncludeHiddenColumn)) { //Paste the copied value with hidden columns. if (dataGrid.Columns.Count <= i) break; PasteToCell(selectedRecords, dataGrid.Columns[i], copyValue[columnindex]); columnindex++; } else { if (dataGrid.Columns.Count <= i) break; //Paste the copied value without hidden columns. if (!dataGrid.Columns[i].IsHidden) { PasteToCell(selectedRecords, dataGrid.Columns[i], copyValue[columnindex]); columnindex++; } else cellcount++; } } } } }