Pages

Thursday, 18 April 2013

How to Bind XML Data in WPF DataGrid using Dataset and List?

How to Bind XML Data in WPF DataGrid using Dataset and List?

In this tutorial I will try to bind XML data in WPF DataGrid by using Dataset and List. Lets say you have XML file from which you have to read data and show in the WPF datagrid. You can do this task by two methods.

Method 1: Using Dataset

In this approach, I wll read XML file into a dataset and then make a dataview from that dataset and then I will assign that dataview to datagrid. Following is the simple C# code for this.

 private void BindGridUsingDataSet()
 {
     string sampleXmlFile = @"C:\MyWPFApp\MyXMLFile.xml";
     DataSet dataSet = new DataSet();
     dataSet.ReadXml(sampleXmlFile );     
     DataView dataView = new DataView(dataSet.Tables[0]);
     dataGrid1.ItemsSource = dataView;
 }


Method 2: Using List

I will load XML file into XElement and then I will go on adding all the elements into list and finally I will bind the list to the datagrid. Have a look at following C# code for this.

class college
{
   public string name { get; set; }
   public string roll { get; set; }
   public string marks { get; set; }
}

private void BindGridUsingList()
{
     string sampleXmlFile = @"C:\MyWPFApp\MyXMLFile.xml";
     XElement xElement = XElement.Load(sampleXmlFile);
     IEnumerable<XElement> students = xElement.Elements();
     List<college> lstCollege = new List<college>();
     // Read the entire XML
     foreach (var student in students)
     {
          lstCollege.Add(new college {name=student.Element("name").Value,roll=student.Element("roll").Value,marks=student.Element("marks").Value});
     }    
     dataGrid1.ItemsSource = lstCollege;
}


Here is the code of datagrid in XAML file

<DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="276,21,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" >
    <DataGrid.Columns>
         <DataGridTextColumn Header="name" Binding="{ Binding  name}" />
         <DataGridTextColumn Header="roll" Binding="{ Binding  roll}" />
         <DataGridTextColumn Header="marks" Binding="{ Binding  marks}" />
    </DataGrid.Columns>
</DataGrid>


Here is the sample XML file

<college>
  <student>
      <name>ABC</name>
      <role>12</role>
      <marks>90</marks>
  </student>
  <student>
     <name>XYZ</name>
     <role>13</role>
     <marks>98</marks>
  </student>
</college>

No comments:

Post a Comment