0

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
ORION
  • 7
  • 7

3 Answers3

1

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

Tomtom
  • 9,087
  • 7
  • 52
  • 95
0

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;
}
James
  • 80,725
  • 18
  • 167
  • 237
0
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?

Community
  • 1
  • 1
George87
  • 102
  • 2
  • 9