user1649078
user1649078

Reputation: 21

Save the selected items from WPF ListView to another variable

I'm trying to get the selected items from ListView (WPF System.Windows.Controls.ListView) and pass it to another variable to store choice but I get a NullReferenceException.

List<LViewItem> onlySelectedItems = null;
var selectedItems = listView1.SelectedItems;

foreach (var item in selectedItems)
{
    onlySelectedItems.Add((LViewItem)item);  // Throws NullReferenceException
}

How can I save the selected items to another variable to store choice?

Upvotes: 2

Views: 2120

Answers (2)

Erre Efe
Erre Efe

Reputation: 15557

The problem is because you're not initializing the onlySelectedItems list.

List<LViewItem> onlySelectedItems = new List<LViewItem>(listView1.SelectedItems.Count);

The parameter in the constructor guidance how many space to allocate for the list (the initial capacity). Which has sense to be the number of selected items.

Anyway, be aware there are other approaches that try to maintain a cleaner correlation between your view and your model (MVVM), give it a try if you have the time. It will pay you back in productivity and clear separation of concerns. It doesn't need to be from scratch. Frameworks like MVVM Light and Caliburn Micro will provide you with the necessary plumbing.

Upvotes: 4

Zabavsky
Zabavsky

Reputation: 13640

Your onlySelectedItems is null. Initialize it first

List<LViewItem> onlySelectedItems = new List<LViewItem>();

Upvotes: 3

Related Questions