简体   繁体   中英

How to save ListView selected item

I'm trying to save a ListView selected item and I don't know why I'm getting this error:

"Cannot implicitly convert type 'int' to 'System.Windows.Forms.ListView.SelectedListViewItemCollection'"

I tried this code on the save button:

Settings.Default["SelectedDevice"] = sourceList.SelectedItems; //Works fine

on Form_Load I tried this:

sourceList.SelectedItems = (int)Settings.Default["SelectedDevice"]; //error

I've made a small application where I read the selecteditem from the settings. The code to select the Item in the OnLoad-Event is:

 private void OnLoad(object sender, EventArgs eventArgs)
 {
    int selectedItem = Properties.Settings.Default.SelectedItem;
    if (selectedItem != -1)
    {
       this.listView1.Items[selectedItem].Selected = true;
    }
  }

The Default-Value of my Settings is -1

First of all SelectedItems is a readonly property, it can't be set. Secondly it's a SelectedListViewItemCollection not an int .

If you are trying to store the selected indices of items in your list you would need to do something along the lines of:

// store CSV list of indices
Settings.Default["SelectedItems"] = String.Join(",", listView.SelectedIndices.Select(x => x));
...
// load selected indices
var selectedIndices = ((string)Settings.Default["SelectedItems]).Split(',');
foreach (var index in selectedIndices)
{
    listView.Items[Int32.Parse(index)].Selected = true;
}
sourceList.SelectedItems = (int)Settings.Default["SelectedDevice"]; //error

There is your error.

Please refer to the following. How to select an item in a ListView programmatically?

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.

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