【发布时间】:2010-09-01 23:41:30
【问题描述】:
是否可以将 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");
}
}
这是保存用户控件的最佳主意吗?
【问题讨论】:
-
好奇你为什么要这样做?
-
您要保存什么、事件、属性或什么?按钮没有太多其他功能,您可以通过恢复属性来重新创建它。
-
我和@p.campbell 在一起——你为什么要这样做?
-
@campbell 我正在使用visualbasic powerpack LineShape 用户控件。我想将每个 lineShape 保存到数据库中。 @James 我正在尝试保存事件和设置。
-
@Christopherous 我正在使用 WinForms
标签: c# winforms user-controls