[英]How can I load in Windows Forms? (C#)
我有 2 个 Windows 窗体。 在第二种形式中,我有几个checkedListBoxex,我的问题是当我尝试获取这些支票并将其保存以备下次使用时,它并没有保存它们,也许我在某处犯了一个小错误。 我认为应该是负载问题。
我的代码:
public partial class Form2 : Form
{
readonly Form1 form1;
StringCollection collectionOfTags = new StringCollection();
public Form2(Form1 owner)
{
form1 = owner;
InitializeComponent();
InitializeSecondForm();
}
private void InitializeSecondForm()
{
this.Height = Properties.Settings.Default.SecondFormHeight;
this.Width = Properties.Settings.Default.SecondFormWidth;
this.Location = Properties.Settings.Default.SecondFormLocation;
this.collectionOfTags = Properties.Settings.Default.DICOMTagSettings;
this.FormClosing += SecondFormClosingEventHandler;
this.StartPosition = FormStartPosition.Manual;
}
private void SecondFormClosingEventHandler(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.SecondFormHeight = this.Height;
Properties.Settings.Default.SecondFormWidth = this.Width;
Properties.Settings.Default.SecondFormLocation = this.Location;
Properties.Settings.Default.DICOMTagSettings = this.collectionOfTags;
Properties.Settings.Default.Save();
}
private void button1_Click(object sender, EventArgs e)
{
foreach (string s in checkedListBox1.CheckedItems)
Properties.Settings.Default.DICOMTagSettings.Add(s);
collectionOfTags = Properties.Settings.Default.DICOMTagSettings;
foreach (string s in checkedListBox2.CheckedItems)
Properties.Settings.Default.DICOMTagSettings.Add(s);
collectionOfTags = Properties.Settings.Default.DICOMTagSettings;
foreach (string s in checkedListBox3.CheckedItems)
Properties.Settings.Default.DICOMTagSettings.Add(s);
collectionOfTags = Properties.Settings.Default.DICOMTagSettings;
this.Close();
}
这是它在设置中的样子。
我只是通过输入添加了这个。
在调试时,我可以看到那里有一些项目,但并没有将它们保存在那里。
选中的项目被保存到Properties.Settings.Default.DICOMTagSettings
,然后,它们被加载到collectionOfTags
,但您实际上并没有使用collectionOfTags
来更新选中的项目。
collectionOfTags
变量实际上是多余的(除非您需要它用于其他用途)。 您可以直接从设置访问字符串集合。 将您的代码更改为如下所示。
要保存选中的项目:
Properties.Settings.Default.DICOMTagSettings.Clear();
foreach (string s in checkedListBox1.CheckedItems)
{
Properties.Settings.Default.DICOMTagSettings.Add(s);
}
或者你可以用这个衬垫替换上面的foreach
循环:
Properties.Settings.Default.DICOMTagSettings
.AddRange(checkedListBox1.CheckedItems.Cast<string>().ToArray());
在表单加载时更新选中的项目:
foreach (string s in Properties.Settings.Default.DICOMTagSettings)
{
int index = checkedListBox1.Items.IndexOf(s);
if (index != -1) checkedListBox1.SetItemChecked(index , true);
}
我创建了一个方法:
private void LoadSettings()
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
var d = checkedListBox1.Items[i];
if (collectionOfTags.Contains(d.ToString()))
{
int index = checkedListBox1.Items.IndexOf(d);
if (index != -1)
checkedListBox1.SetItemChecked(index, true);
}
}
}
将此方法放在构造函数中:
public Form2(Form1 owner)
{
form1 = owner;
InitializeComponent();
InitializeSecondForm();
LoadSettings();
}
现在它可以工作了,谢谢@41686d6564 的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.