我有 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();
}
這是它在設定中的樣子。

我只是通過輸入添加了這個。

在除錯時,我可以看到那里有一些專案,但并沒有將它們保存在那里。

uj5u.com熱心網友回復:
選中的專案被保存到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);
}
uj5u.com熱心網友回復:
我創建了一個方法:
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 的幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/339210.html
