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();

santosh nanduriPosted Jan 6, 2011, 4:20 AM
Nice