Enabling copy paste feature in a DataGrid(Silverlight)


Purpose:  In a typical business oriented scenario people wants not only to view data but also to work with that data. It is easy to show data into the datagrid but Silverlight doesn't give us any support to get those data for other works like generating reports based on those raw data etc. We don't have export to excel feature from the datagrid. 

Work Around: One way to get this feature is the "poor man effort" of copy data from the datagrid and then paste it to excel. Unfortunately Silverlight will not let you to copy data also. In this post I will describe how to enable the ExcelBehaviour on a DataGrid.

Solution:

Let's create a Static class called ExcelBehavior. We will be interested in three events of the data grid: KeyUp, GetFocused and CellEditEnded. Reason for this is very simple. To copy the data from the datagrid you need to select the grid using key events and after that it will be Focused. Let's define one simple static method in that class:

public static void EnableForGrid(DataGrid dataGrid)
{
   dataGrid.KeyUp += (s, e) =>
   {
     KeyUpHandler(e, dataGrid);
    };
    dataGrid.GotFocus += (s, e) =>
    {
      GotFocusHandler(dataGrid);
    };
    dataGrid.CellEditEnded += (s, e) =>
    {
      EditEndedHandler(dataGrid);
    };
}

In the KeyUpHandler even we will check whether user is pressing C key or V key and work accordingly. As Silverlight doesn't support clipboard we will use JavaScript to store the data inside clipboard.

private static void KeyUpHandler(KeyEventArgs e, DataGrid dataGrid)
{
    //copy
    if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
    {
        if (e.Key == Key.C)
        {
            var items = dataGrid.SelectedItems;
            if (items.Count == 0) return;
            //don't let it bubble up so nothing else happens
            e.Handled = true;
            //JS supports clipboard, silverlight doesn't, use it
            var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
            clipboardData.Invoke("setData", "text", ExcelBehavior.GetCellData(items, dataGrid));
            MessageBox.Show("Your data is now available for pasting");
        }
        else if (e.Key == Key.V)
        {
            var items = dataGrid.SelectedItems;
            object startObject = (items.Count > 0 ? items[0] : null);
            //don't let it bubble up so nothing else happens
            e.Handled = true;
            //JS supports clipboard, silverlight doesn't, use it
            var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
            string textData = clipboardData.Invoke("getData", "text").ToString();
            ExcelBehavior.SetCellData(startObject, dataGrid, textData);
        }
    }
    else
    {
        //don't start editing for nav keys so a left arrow, etc. doesn't put text in a box
        if (dataGrid.Tag == null && !IsNavigationKey(e) && !dataGrid.CurrentColumn.IsReadOnly)
        {
            bool isShifty = ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift);
            string letter = ((char)e.PlatformKeyCode).ToString();
            letter = (isShifty ? letter.ToUpper() : letter.ToLower());
            dataGrid.Tag = letter;
            //beginedit will fire the focus event
            //if we try to access the textbox here its text will not be set
            dataGrid.BeginEdit();
        }
    }
}

The GetCellData method is typically used to get all the data which are selected by the user. The method construction is simple. It will return null if nothing is there inside the grid other wise it will enamurate all the columns and get the cell content.

private static string GetCellData(IEnumerable items, DataGrid dataGrid)
{
    if (dataGrid.ItemsSource == null) return null;
    //build row-newline delim, column tab delim string
    var sb = new StringBuilder("");
    //add headers first
    var rowData = new List<string>();
    var columnData = new List<string>();
    foreach (var column in dataGrid.Columns)
    {
        var cellData = column.Header;
        if (cellData != null)
            columnData.Add(cellData.ToString());
    }
    rowData.Add(String.Join("\t", columnData.ToArray()));
    //for each selected item get all column data
    foreach (var item in items)
    {
        columnData = new List<string>();
        foreach (var column in dataGrid.Columns)
        {
            //cells that are scrolled out of view aren't created yet and won't give us their content
            //therefore we engage in some STSOOI behavior to get er' done
            dataGrid.ScrollIntoView(item, column);
            columnData.Add(GetCellText(item, column));
        }
        rowData.Add(String.Join("\t", columnData.ToArray()));
    }
    sb.Append(String.Join(Environment.NewLine, rowData.ToArray()));
    string textData = sb.ToString();
    return textData;
}

I am attaching the whole class file with this post. I tried to give appropriate comments to better understanding of the class. To use this class you need to simply use the EnableForGrid method and pass the datagrid as ExcelBehavior.EnableForGrid(datagrid);

Now you can copy paste your data from the datagrid and use it for your internal use.

Up Next
    Ebook Download
    View all
    Learn
    View all