是否可以将用户控件保存到数据库中

时间:2010-09-01 23:41:30

标签: c# winforms user-controls

是否可以将WinForms用户控件(例如:按钮)保存到数据库? 或者唯一可以保存的是设置属性。

修改 就像triggerX所说的那样。我测试了可序列化的想法。

btnAttrib.cs

[Serializable()]
class btnAttrib
{
    public Point LocationBTN { get; set; }
    public Size SizeBTN { get; set; }
    public string NameBTN { get; set; }

    public btnAttrib(Point l, Size s, string n) 
    {
        this.LocationBTN = l;
        this.SizeBTN = s;
        this.NameBTN = n;
    }
}

MainForm.cs

 private void button2_Click(object sender, EventArgs e)
    {
        var btnAttr = new List<btnAttrib>();

        btnAttr.Add(new btnAttrib(new Point(50, 100), new Size(50, 50), "Button 1"));
        btnAttr.Add(new btnAttrib(new Point(100, 100), new Size(50, 50), "Button 2"));
        btnAttr.Add(new btnAttrib(new Point(150, 100), new Size(50, 50), "Button 3"));
        btnAttr.Add(new btnAttrib(new Point(200, 100), new Size(50, 50), "Button 4"));

        try
        {
            using(Stream st = File.Open("btnSettings.bin", FileMode.Create)) {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(st, btnAttr);
            }
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message, "Exception");
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try {
            using (Stream st = File.Open("btnSettings.bin", FileMode.Open)) {
                BinaryFormatter bf = new BinaryFormatter();

                var btnAttr2 = (List< btnAttrib>)bf.Deserialize(st);
                foreach(btnAttrib btAtt in btnAttr2) {

                    Button nBTN = new Button();
                    nBTN.Location = btAtt.LocationBTN;
                    nBTN.Size = btAtt.SizeBTN;
                    nBTN.Name = btAtt.NameBTN;

                    this.Controls.Add(nBTN);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exception");
        }
    }

这是保存用户控件的最佳方法吗?

1 个答案:

答案 0 :(得分:2)

答案是模糊的“是”,通过序列化其属性/设置,您可以产生将控件保存到数据库的错觉。