SIGN UP MEMBER LOGIN:    
ARTICLE

Enabling copy paste feature in a DataGrid(Silverlight)

Posted by Arunava Bhattacharjee Articles | Silverlight with C# July 15, 2010
In this post I will describe how to enable the ExcelBehaviour on a DataGrid.
Reader Level:
Download Files:
 

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.

Login to add your contents and source code to this article
share this article :
post comment
 

Nice

Posted by santosh nanduri Jan 06, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor