obind
obind

Reputation: 195

Properties.Settings does not save list view items

Hey Im working on a software solution and I have a listview in my program and would like to save it.

var listview = new List<string>();
    foreach (ListViewItem Item in listView1.Items)
    {
       listview.Add(Item.Text.ToString());
    }
StringCollection collection = new StringCollection();
Properties.Settings.Default.ListViewItems = collection;
Properties.Settings.Default.Save();

Im tryring to save it with settings but when i try to call it the value is null

here is my list

But when i try to load my table i cant do it like so. When i'm trying to call my table it isnt working like this.

var collection = Properties.Settings.Default.ListViewItems;
    if (collection != null)
    {
        List<string> list = collection.Cast<string>().ToList();
        foreach (var item in list)
        {
            listView1.Items.Add(item);
        }
    }
    else
    {
        MessageBox.Show("null");
    }

Upvotes: 0

Views: 195

Answers (1)

Dai
Dai

Reputation: 155270

So you have items in listView1.Items and you want to save them to the WinForms Settings system.

Do it like so:

var settings = Properties.Settings.Default;
if( settings.ListViewItems is null ) settings.ListViewItems = new StringCollection();
foreach( ListViewItem lvi in listView1.Items )
{
    settings.ListViewItems.Add( lvi.Text );
}
settings.Save();

Annoyingly, the StringCollection type has a method named AddRange but it only accepts String[] and not IEnumerable<String> - and .NET doesn't come with a stock AddRange method for the non-generic IList. So I recommend you avoid using the Settings system because it's weakly-typed and doesn't play-nice with the modern C# ecosystem, like support for Linq.

Upvotes: 2

Related Questions