繁体   English   中英

C#.Net使用Settings.settings保存ListView

[英]C# .Net Save a ListView using Settings.settings

我正在尝试使用C#.Net保存和加载ListView列表的内容。 我希望通过创建变量System.Windows.Forms.ListView并随后填充它来保存它。

保存的代码段:

Properties.Settings.Default.followedUsersSettings = followerList;
Properties.Settings.Default.Save();

加载代码段:

if (Properties.Settings.Default.followedUsersSettings != null) {
            followerList = Properties.Settings.Default.followedUsersSettings;
        }

我似乎无法使用该代码来工作。 有没有更好的方法来尽可能简单地保存它? 该列表是单列,因此数组也应该起作用,但是我不确定推荐什么。

好的,我设法使其正常工作。

保存:

//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();

对于加载:

//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);
    }
}

希望对从Google搜索中找到此内容的人有意义。

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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM