Telerik blogs

Did you know that you can serialize any DataTable to Silverlight easily from your custom WCF service in very few lines of code?

[OperationContract]
public IEnumerable<Dictionary<string, object>> GetData()
{
    var table = YourDataTable;

    var columns = table.Columns.Cast<DataColumn>();

    return table.AsEnumerable().Select(r => columns.Select(c =>
                         new { Column = c.ColumnName, Value = r[c] })
                     .ToDictionary(i => i.Column, i => i.Value != DBNull.Value ? i.Value : null));
}

 

I’ve made small update for my lightweight DataTable for Silverlight and now you can create the table directly from IEnumerable<Dictionary<string, object>>:

namespace Telerik.Data
{
    public class DataTable : IEnumerable
    {
        public DataTable(IEnumerable<Dictionary<string, object>> source)
        {
            ...
}
    }
}

Now you can use all these to serialize any DataTable with unknown number of columns and types to the Silverlight client and bind desired control:

XAML
<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
    xmlns:telerik="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.GridView">
    <Grid x:Name="LayoutRoot">
        <telerik:RadGridView x:Name="RadGridView1" />
    </Grid>
</UserControl>



C#

using System.Windows.Controls;
using SilverlightApplication1.ServiceReference1;
using Telerik.Data;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            var client = new MyServiceClient();
            client.GetDataCompleted += (s,e) => 
            {
                RadGridView1.ItemsSource = new DataTable(e.Result);
            };

            client.GetDataAsync("SELECT CustomerID, CompanyName, ContactName, City, Country, Address, Fax FROM Customers");
        }
    }
}


The result - fully functional dynamic DataGrid and DataTable:
 image

Enjoy!

 


About the Author

Vladimir Enchev

is Director of Engineering, Native Mobile UI & Frameworks

Comments

Comments are disabled in preview mode.