ORION
ORION

Reputation: 7

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

Upvotes: 0

Views: 1654

Answers (3)

Tomtom
Tomtom

Reputation: 9394

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

Upvotes: 1

James
James

Reputation: 82136

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

Upvotes: 0

George87
George87

Reputation: 92

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?

Upvotes: 0

Related Questions