How to perform WPF Data Binding using LINQ to XMLvb.net
Step 1) Create WPF project using vb.net 4.0/4.5
Step 2) Add Xml file to Project . name it as salesorder.xml
<?xml version="1.0" encoding="utf-8" ?>
<HeaderLines>
<SalesOrder>
<Header Date="17-02-04" Type="Quote">
<SellTo CountryRegion="GB">
<Name>The Cannon Group PLC</Name>
<Address>192 Market Square</Address>
<City>Birmingham</City>
<Zip>B27 4KT</Zip>
</SellTo>
<BillTo CountryRegion="GB">
<Name>The Cannon Group PLC</Name>
<Address>192 Market Square</Address>
<City>Birmingham</City>
<Zip>B27 4KT</Zip>
</BillTo>
<Lines>
<Item PartNum="LS-150">
<ProductName>Loudspeaker, Cherry, 150W</ProductName>
<Quantity>8</Quantity>
<UnitPrice>12900</UnitPrice>
<ShipmentDate />
<Comment>Confirm the voltage is 75W</Comment>
</Item>
<Item PartNum="LS-MAN-10">
<ProductName>Manual for Loudspeakers</ProductName>
<Quantity>20</Quantity>
<UnitPrice>100</UnitPrice>
<ShipmentDate />
<Comment />
</Item>
<Item PartNum="LS-2">
<ProductName>Cables for Loudspeakers</ProductName>
<Quantity>10</Quantity>
<UnitPrice>2100</UnitPrice>
<ShipmentDate />
<Comment />
</Item>
</Lines>
<Contact>Mr. Andy Toal</Contact>
<Terms>14 days</Terms>
</Header>
</SalesOrder>
</HeaderLines>
Step 3) Add datagrid to XAML
<DataGrid x:Name="datagrid4" HorizontalAlignment="Left" VerticalAlignment="Top" Height="218" Width="275" Margin="10,53,0,0"/>
<Label Content=" Datagrid Binding in WPF using LINQ to XML" HorizontalAlignment="Left" VerticalAlignment="Top" Height="48" Width="290" Foreground="Aquamarine" FontSize="20"/>
Step 4) LINQ TO XML in WPF
Private Function XMLDemo() As Public
InitializeComponent()
LoadXml()
End Function
Private Sub LoadXml()
Try
Dim doc As XDocument = XDocument.Load("SalesOrder.xml")
If doc Is Nothing Then
MessageBox.Show("doc is null")
End If
var query = from ele Function doc.Descendants(ByVal"Item") As in
ProductName = ele.Element("ProductName").Value,
Quanity = ele.Element("Quantity").Value,
UnitPrice = ele.Element("UnitPrice").Value,
Total = Convert.ToInt32(ele.Element("Quantity").Value) *
Convert.ToDouble(ele.Element("UnitPrice").Value)
End Function
datagrid4.ItemsSource = query.ToList()'Binding linq to xml list to datagrid
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show(ex.InnerException.Message)
End Try
End Sub
Step 5) Run the Applictaion
No comments:
Post a Comment