简体   繁体   中英

How to save dynamically created objects

I'm Looking for a solution to save my dynamically created picture boxes and their settings. I'm not too sure how I would go about this. Also these Picture boxes need to be loaded back into the program when the form loads.

Maybe they could be saved to a database, how would we do that?

Code to create the picture boxes

    PictureBox picturebox1 = new PictureBox();
    picturebox1.Name = "picturebox1";
    picturebox1.Size = new Size(48, 48);
    picturebox1.BackgroundImage = Properties.Resources.FolderIcon;
    myFlowLayoutPanel1.Controls.Add(picturebox1);

Any ideas are very welcomed. Thank you.

Serialing a small collection of controls is not difficult. If there is already a database for the project, I might use that instead.

The first issue is that controls cannot be serialized directly. You need a class to hold the data needed to recreate them:

<Serializable>
Friend Class CtlItem
    Public Property Location As Point
    Public Property Size As Size
    Public Property BackColor As Color
    Public Property Text As String

    ' some serializers require a simple ctor
    Public Sub New()

    End Sub
    ' create object from passed PB
    Public Sub New(pb As Button)
        Location = pb.Location
        Size = pb.Size
        BackColor = pb.BackColor
        Text = pb.Text
    End Sub
End Class

I am using buttons in place of pictureboxes but the concept is the same. Many serializers require the <Serializable> attribute and a simple ctor. Rather than setting all the props in code, I let the class harvest the ones I need to save. You will need to extend this to save all non default properties for your controls.

Getting the data, serializing and testing the round trip:

' collection for many control descriptors
Dim btns As New List(Of CtlItem)

' collect the data for some controls
For Each btn In TabPage1.Controls.OfType(Of Button)()
    btns.Add(New CtlItem(btn))
Next
' serialize the list 
Using fs As New FileStream("C:\Temp\Buttons.bin", FileMode.OpenOrCreate)
    fs.Position = 0
    Dim bf As New BinaryFormatter
    bf.Serialize(fs, btns)
End Using

' round trip test
Dim newBtns As List(Of CtlItem)
Using fs As New FileStream("C:\Temp\Buttons.bin", FileMode.Open)
    Dim bf As New BinaryFormatter
    newBtns = CType(bf.Deserialize(fs), List(Of CtlItem))
End Using

This uses the BinaryFormatter to serialize, but the XMLSerialzer, Protobuf-Net and json all work pretty much the same. The initial collection has 19 buttons, the first one is "files". The images show the newBtns colelction has the same number and at least the first one matches (serialization is usually an all or nothing proposition). The btns collection, before:

在此处输入图片说明

The newBtns collection, after: 在此处输入图片说明

Your code would then recreate the controls from that data and add them to the form. This could get complicated if they come from different Control collections and of course restoring an image. The core code could be in the CtlItem class:

Friend Function NewButton() As Button
    Dim btn As New Button
    btn.Location = Location
    btn.Text = Text
    btn.BackColor = BackColor
    '...
    Return btn
End Function

I would recommend saving in DB if the images are not too big (or are not custom). Your table would look something like this (run the script in MS-SQL management console ):

CREATE TABLE dbo.picturebox     (
    pbID int NOT NULL,
    pbName nvarchar(50) NOT NULL,
    pbSize1 float(53) NULL,
    pbSize2 float(53) NULL,
    pbBackGroundImage image NULL
    )  ON [PRIMARY]
     TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE dbo.picturebox SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

(Of course you'll need to add your SQL CRUD code.)

Hopefully this is enough to get you started.

OK i'll add the basic T-SQL insert code, but please read the following: http://www.dreamincode.net/forums/topic/103960-save-and-retrieve-images-with-sql-server/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM