Wednesday, November 10, 2010

Binding Silverlight DataGrid with XML file

Hello All,
In this article I would like to discuss about binding value to a Silver light DataGrid. As we know that there is no direct support for the Dataset or DataTable in the Silver light, so how can we bind the grid??? See there are multiple option for binding the grid in silver light either we can use the-
  1. 1. Collection of the Item Class,
  2. or a Dictionary or
  3. we can also use a XML File
In this article I am going to describe the way to bind a XML file that is present in the server Side, that means a User XML file can be bind to the grid in the Silver light form.Here I am Making use of LINQ to read the data from XMl file.

first We Will see that how can we access the XML file and its element. Please check the below Code.

private void getDatFromXML()
Uri newURL = new Uri("mydata.xml", UriKind.Relative);
WebClient cnt = new WebClient();
cnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cnt_DownloadStringCompleted);

Private void cnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
dataGrid1.ItemsSource = ReadListItem(e.Result);

public List<Item> ReadListItem(string xmlContent)
List<Item> il = new List<Item>();
XElement doc = XElement.Parse(xmlContent);
il = (from ele in doc.Elements()
select GetItem(ele)).ToList();
return il;

You have seen that how first we downloaded the file from the server machine and then reading its content to bind the Grid. Here ReadListItem is a generic function which returns us the LIST ITEM collection, the collection can be easily bind to the Silver light data grid. We just have to set the ItemSource property of the Silver Light Data Grid. like.

dataGrid1.ItemsSource = ReadListItem(e.Result);

I hope you have Got the Idea. Please look at the XAML part of the XML file that how the content looks.

<UserControl x:Class="DataBinding.MainPage" xmlns="" xmlns:x=""
xmlns:d="" xmlns:mc="" mc:Ignorable="d"
d:DesignHeight="513" d:DesignWidth="662" xmlns:sdk="">

<Grid x:Name="LayoutRoot" Background="White" Height="600" Width="600">
<sdk:DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="20,30,0,0" Name="dataGrid1" VerticalAlignment="Top"Width="450" />

Hope You Understood the Way to bind the DataGrid in Silver light by a XML file. Please feel free to post the comments.

Anil Kumar Pandey
MVP (Visual C#)