Reputation: 21
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
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
Reputation: 13640
Your onlySelectedItems
is null. Initialize it first
List<LViewItem> onlySelectedItems = new List<LViewItem>();
Upvotes: 3