c# - 如何在 Windows 窗体中加载?(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);
}
推荐阅读
- mysql - 如何创建超过 8 个表和特殊条件的多选
- node.js - Send Rendered React component to Function App(Node Js) in AZURE to create a PDF
- mysql - 如何使用 NiFi 解析/提取属性名称及其值
- python - 应用熊猫组功能保留其他列
- python - 可视化傅立叶变换的计算有效方法?
- hyperledger-fabric - 有没有办法使用 Hyperledger Composer 设置多个对等点?
- r - 将栅格中的值替换为另一个栅格中的值
- python - Django:省选择字段依赖于州选择字段
- c# - 如何在 UWP 中设置 CommandBarFlyout 的主题?
- timestamp - 在 PowerBI (Desktop) 中,如何对每天(或每周或每月)的时间戳进行分组?