Introduction
This article helps you brush up the advanced concepts of XML Serialization and abstract
class as well.
Using the Code
Orderlist class contains two main modules; SaveOrder
which is used to serialize the object and generate the XML file. ReadOrder
is a shared function which is used to deserialize it into an object.
Public Sub SaveOrder()
Try
Dim xs As XmlSerializer = New XmlSerializer(GetType(OrderList))
Dim sw As StreamWriter
sw = New StreamWriter(Application.StartupPath & "\Order\Order.xml")
xs.Serialize(sw, Me)
sw.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Shared Function ReadOrder() As OrderList
Dim sr As StreamReader
Dim xs As XmlSerializer = New XmlSerializer(GetType(OrderList))
Try
sr = New StreamReader(Application.StartupPath & "\Order\Order.xml")
Dim r_order As OrderList = DirectCast(xs.Deserialize(sr), OrderList)
sr.Close()
Return r_order
Catch ex As Exception
MsgBox(ex.ToString)
Return Nothing
End Try
End Function
In this example, I have used the DataGridView
control to display the placedorder which is stored in an XML file. To display data in DataGridView
, I have created a DataTable
and created the DataColumn
s according to PlacedOrder
. Using the collection of Placedorders
, I have added data one in DataTable
using DataRow
.
Private Sub cmdReadOrder_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdReadOrder.Click
Dim r_orderList As OrderList = OrderList.ReadOrder()
If Not (r_orderList Is Nothing) Then
m_OrderList = r_orderList
End If
Dim dt As New DataTable
Dim dr As DataRow
dt.Columns.Add("CUSTOMER")
dt.Columns.Add("TABLENO")
dt.Columns.Add("MENUITEM")
dt.Columns.Add("QTY")
dt.Columns.Add("TASTE")
dt.Columns.Add("FAT")
For Each ord As Order In r_orderList.Orders
dr = dt.NewRow
dr("CUSTOMER") = ord.m_Customer
dr("TABLENO") = ord.m_TableNo
dr("MENUITEM") = ord.m_menuitem
dr("QTY") = ord.m_OrderQty
dr("TASTE") = ord.m_Taste
dr("FAT") = ord.m_Fat
dt.Rows.Add(dr)
Next
DataGridView1.DataSource = dt
DataGridView1.Columns("CUSTOMER").Width = 95
DataGridView1.Columns("TABLENO").Width = 60
DataGridView1.Columns("QTY").Width = 40
DataGridView1.Columns("TASTE").Width = 60
DataGridView1.Columns("FAT").Width = 60
End Sub
History
Visit XML Serialization - Part 1.
I have submitted XML Serialization Part I. In the XML Serialization - Part 1 article, you can serialize only one instance of an object. If the user wishes to pass through more than one order, he has to create a separate XML file for each placed Order.
XML Serialization - Part 2 removes this constraint. You can place multiple orders with different values and create a list of it. You can even remove your placed order before you do serialization.