How can de-serialize a .dat file to create controls on a form?

后端 未结 2 1594
清酒与你
清酒与你 2021-01-28 05:56

I have managed to serialize each object on a panel and put it into a .dat file with some properties (I\'ll do all of the possible properties at a later date). This file looks li

相关标签:
2条回答
  • 2021-01-28 06:22

    You may not want to actually read the XML file. Whatever the controls where in (list(of?), collection?) when it was serialized, the XML can deserialize to that same thing which might make it easier. For instance, if you serialized a collection of classes containing those properties, you could get that back.

    Otherwise, read the XML into a datatable maybe (there are other ways):

    Dim ds As New DataSet()
    Dim dt as New DataTable
    ' Create new FileStream with which to read the file
    Dim fsReadXml As New System.IO.FileStream _
        (myXMLfile, System.IO.FileMode.Open)
    Try
        ds.ReadXml(fsReadXml)
    
    Catch ex As Exception
        MessageBox.Show(ex.ToString())
    Finally
        fsReadXml.Close()
    End Try
    dt = ds.Tables(0)
    

    then loop thru the table to fetch the property values to NEW controls you add to the parent's controls array. The dt.Rows will each contain 1 control's data, the columns will hold each property. Since you created the file, you know what the column names are and can reference them by name:

    For each dr as Datarow  In ds.Tables(0).Rows
        Dim lbl as New Label
    
        With lbl
         .Top = dr.Item("Top")
         ' etc etc etc
        End with
    
       ' add to parent
        pnlThing.Controls.Add(lbl)
    
     Next
    

    The thing you will run into with an XML source is that if there are different kinds of controls in there, you will need to save the ctl.Type as well, but then Parse out what kind of control it is from the name.

    Edit: A binary serializer is easier:

        For Each ctl As Control In pnl1.Controls
            Dim c As New Class1
            c.sz = ctl.Size
            c.pt = ctl.Location
            c.name = ctl.Name
    
            L.Add(c)
        Next
    
        ' Persist to file
        Dim stream As FileStream = File.Create("C:\Temp\bin.dat")
        Dim formatter As New BinaryFormatter()
        formatter.Serialize(stream, L)         ' NOTE serialize the LIST of Class1
        stream.Close()
    

    When you deserialize, you will have a new List(of Class1) with all the props that you can ref in "groups" or sets of stuff you already know Like SIZE instead of Width And Height. It wont handle a Controls array apparently hence the need to collect whatever you need.

    0 讨论(0)
  • 2021-01-28 06:26

    What about assigning the values with reflection? Kind of:

    var control = FindByName(...);
    
    foreach (var node in xmlNode.Children) {
        typeof(control).GetProperty(node.Name).SetValue(control, node.InnerText)
    }
    
    0 讨论(0)
提交回复
热议问题