Link to home
Start Free TrialLog in
Avatar of lep1
lep1

asked on

VB.NET: Serialize and Deserialize a UserControl's Data

I am using the code below to show a dynamic form containing a UserControl which is encapsulated into a class. The class is to be serialized so that (a) the properties of usercontrol objects can be saved, (b) the class can undergo garbage collection once closed, and (c) when a user wants to modify the usercontrol the deserialize routine would be called and the usercontrol with saved properties appears.

It is not clear whether I can user many usercontrols in a class, selected by case, which would prevent using a separate class for each usercontrol.

Below is the code thus far:
    <Serializable()> Public Class MyUC1 'one user control per class 
        Public Sub New()
            Dim myform As New Form
            myform.Show()
            Dim mycntl As New MyUserControlLibrary.myuc1
            myform.Controls.Add(mycntl)
            Dim btn As New Button
            btn.text = "Apply"
            btn.Top = 300
            btn.Left = 10
            myform.Controls.Add(btn)
            AddHandler btn.Click, AddressOf Form1.serialize
        End Sub
    End Class

    Public Class Form1

        ....

        Private Sub Button8_Click(sender As System.Object, e As System.EventArgs) Handles Button8.Click
            Dim cntl As New MyUC1
        End Sub
        Sub serialize()
            Dim cntl As New MyUC1
            Dim ser As New XmlSerializer(GetType(MyUC1))
            ' Open the destination file.
            Dim fs As New FileStream("C:\Leifuse\VBNet 2010\NXG Without ShapeContainer\superperform.xml", FileMode.Create)
            ' Serialize the object to the stream, enforcing the specified namespaces.
            ser.Serialize(fs, cntl)
            fs.Close()
        End Sub
        Private Sub Button10_Click(sender As System.Object, e As System.EventArgs) Handles Button10.Click
            Dim deser As New XmlSerializer(GetType(MyUC1))
            Dim fs As New FileStream("C:\myuc1.xml", FileMode.Open)
            Dim cntl As MyUC1 = CType(deser.Deserialize(fs), MyUC1)
            fs.Close()
        End Sub
    End Class

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial