Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Silverlight » Enabling copy paste feature in a DataGrid(Silverlight)

Enabling copy paste feature in a DataGrid(Silverlight)

In this post I will describe how to enable the ExcelBehaviour on a DataGrid.

Page Views : 4846
Downloads : 140
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ExcelBehavior.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Arunava Bhattacharjee

I am interested in Microsoft Technologies. I love to experiment and learn new technologies. I have exposure on Silverlight 2, Silverlight 3, Blend 2, Blend 3, WCF, ASP.NET and C#.

 Reach me @ arunava.bhattacharjee@gmail.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
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!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Great by santosh On January 6, 2011
Nice
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.