【发布时间】:2011-11-08 12:33:42
【问题描述】:
我是 C# 新手,所以请解决我的新手问题。
我从一个名为 dictControls 的 Windows 窗体创建了一个控件字典。然后我用表单中的所有文本框和组合框控件和值填充它:
Dictionary<Control, string> dictFormControls = new Dictionary<Control, string>();
foreach (Control c in Controls)
{
if (c is ComboBox)
{
dictFormControls.Add(c, ((ComboBox)c).SelectedValue.ToString());
}
if (c is TextBox)
{
dictFormControls.Add(c, ((TextBox)c).Text);
}
if (c is MaskedTextBox)
{
dictFormControls.Add(c, ((MaskedTextBox)c).Text);
}
}
if (discNumber <= Convert.ToInt32(numDiscs))
{
frmAddVideo frm = new frmAddVideo(numDiscs, discNumber, videoID, sequenceID, dictFormControls);
frm.Show();
this.Close();
}
我希望字典基本上看起来像这样:
键------------值
“txtName”-----“测试”
"txtYear" ------ "1980"
我将其传递回相同的表单 (frmAddVideo):
public frmAddVideo(string numDiscs, int discNumber, string videoID, string sequenceID, Dictionary<Control, string> dict)
{
this.numDiscs = numDiscs;
this.discNumber = discNumber;
this.videoID = videoID;
this.sequenceID = sequenceID;
InitializeComponent();
//This is where I want to parse out the Dictionary and populate the form values
foreach (KeyValuePair<Control, string> item in dict)
{
**Basically, I am looking for a way to take **
**item(Key)**
**and do something like item(Key).Value = item(Value);**
**so it would be the same as writing**
**txtName.Text= "1980";**
**cbxLocID.Value = 1;**
}
}
我正在寻找一种方法来获取键并将其转换为控件名称,然后将“.Text”或“.Value”添加到它,然后将值设置为 item(value),如我在上面的代码中解释的那样.
这可能吗?我试着研究这个,但我还没有把 2 和 2 放在一起。
【问题讨论】:
-
您只是想保留数据吗?如果是这样,您可以尝试序列化表单而不是手动保存所有内容。
-
如果这是新的,请使用 WPF。
-
@Jodrell 切换到 WPF 对他有何帮助?
-
谁说这是推荐的方式,只是因为它较新?如果他只是在学习 C#,那么做 WPF 只会使他的学习复杂化,因为他必须涉足所有的 WPF bs。您的评论没有建设性。
-
首先,感谢大家的回复。我是 C# 新手,基本上我有一个在 Save 上调用自身的 Windows 窗体。我正在尝试使用表单中的信息预填充一些文本框和组合框。我想我可以通过使用控制(键)和值(值)的字典来做到这一点,将它传递回构造函数,然后循环并解析出键(这是表单上控件的名称)和价值。我这样做只是为了学习。我从 Windows 窗体开始,这样我可以在走路之前学会爬行,可以这么说。 :)
标签: c# winforms dictionary controls