I am trying to maintain a list of checked items in a CheckedListBox
in User Settings and then reload them upon Application load.
In my Settings.settings
file, I added the following:
<Setting Name="obj" Type="System.Windows.Forms.CheckedListBox.ObjectCollection" Scope="User">
<Value Profile="(Default)" />
</Setting>
And, on chkList_ItemCheck
, I am doing the following:
Properties.Settings.Default.obj = chkList.Items;
Properties.Settings.Default.Save()
But for some reason, when I exit the app, re-open, and check the value of Properties.Settings.Default.obj
, it is null
.
What am I doing wrong/missing?
Since
CheckedListBox.CheckedItems
property in not bindable to settings, you should add a string property and store checked items as comma separated string in settings and save settings when closing the form and set checked items of CheckedListBox at form Load.To save
CheckedItems
of aCheckedListBox
:Settings
file to your project inProperties
folder, or if you have that open it.CheckedItems
Load
event of form, read checked items from settings, and set checked items in CheckedListBox usingSetItemChecked
.FormClosing
event, readCheckedItems
of CheckedListBox and save in setting as comma separated string.Code:
How do I know it is not bindable to settings?
As first evidence, for each control in designer mode, in property grid, you can check +(
ApplicationSettings
) (PropertyBinding
)[...] to see a list of properties that support property binding.Furthermore, you should know "Application settings uses the Windows Forms data binding architecture to provide two-way communication of settings updates between the settings object and components."[1]
For example when you bind
BackColor
property of yourCheckedListBox
to aMyBackColor
property, here is the code that the Designer generates for it:Now let's look at property definition [2]:
Is there a better way?
The short answer for this property is No.
Suppose we have a property
MyCheckedItems
:How can we or setting provider instantiate
CheckedListBox.CheckedItemCollection
?So we can not instantiate it. The only constructor that CheckedListBox internally use it is [2]:
Furthermore the only way to add an item to this collection is an internal method of
CheckedItemCollection
:So we can't do a better workaround for this property.
More information:
ApplicationSettings
) (PropertyBinding
)[...] to see a list of properties that support property binding.ConvertToString
orConvertFromString
on the type's associatedTypeConverter
. If this does not succeed, it uses XML serialization instead. [1] So For cases that you are not faced with read only properties or constructor-less classes, you can serialize value using a customTypeConverter
or a custom serializer.