Is it possible to save a user control to the database
Is it possible to save a WinForms user control(ex: button) to the database? Or the only thing that can be saved is the settings property.
EDIT开发者_JAVA技巧: Like what triggerX said. I tested the serializable idea.
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");
}
}
Is this the best Idea for saving user controls?
the answer is a vague "yes", by serializing its properties/settings you can have the illusion that you are saving the control to the database.
精彩评论