I'm trying to save and load the contents of a ListView list using C# .Net. I was hoping to save it by creating a variable System.Windows.Forms.ListView and then populating it with that.
Code snippet for Saving:
Properties.Settings.Default.followedUsersSettings = followerList;
Properties.Settings.Default.Save();
Code snippet for Loading:
if (Properties.Settings.Default.followedUsersSettings != null) {
followerList = Properties.Settings.Default.followedUsersSettings;
}
I can't seem to get it to work using that code. Are there any better ways of saving this that is as simple as possible? The list is single column, so an Array should also work, but i'm not sure what is recommended.
ok, I managed to get it working.
Saving:
//Convert the listview to a normal list of strings
var followerList = new List<string>();
//add each listview item to a normal list
foreach (ListViewItem Item in followerListView.Items) {
followerList.Add(Item.Text.ToString());
}
//create string collection from list of strings
StringCollection collection = new StringCollection();
//set the collection setting (created in Settings.settings as a specialized collection)
Properties.Settings.Default.followedUsersSettingsCollection = collection;
//persist the settings
Properties.Settings.Default.Save();
And for Loading:
//check for null (first run)
if (Properties.Settings.Default.followedUsersSettings != null) {
//create a new collection again
StringCollection collection = new StringCollection();
//set the collection from the settings variable
collection = Properties.Settings.Default.followedUsersSettingsCollection;
//convert the collection back to a list
List<string> followedList = collection.Cast<string>().ToList();
//populate the listview again from the new list
foreach (var item in followedList) {
followerListView.Items.Add(item);
}
}
Hopefully that makes sense to someone who found this from a Google search.
if (Properties.Settings.Default.followedUsersSettingsListView == null)
{
// adding default items to settings
Properties.Settings.Default.followedUsersSettingsListView = new System.Collections.Specialized.StringCollection();
Properties.Settings.Default.followedUsersSettingsListView.AddRange(new string [] {"Item1", "Item2"});
Properties.Settings.Default.Save();
}
// load items from settings
followerList.Items.AddRange((from i in Properties.Settings.Default.followedUsersSettingsListView.Cast<string>()
select new ListViewItem(i)).ToArray());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.