Quick Tip: Getting the Collection of Checked ListView Items
Have you ever created a ListView control and wanted to get the collection of items that the user has checked? While I was working on my demo for MEDC, that was one of the things that I needed to be able to do. If I were writing my application for the .NET Framework, I would get the collection of items via the ListView.CheckedItems property. When I looked up ListView in the MSDN documentation, I found that the CheckedItems property is not supported on the .NET Compact Framework. As a result, I was going to need to create the collection myself. Or was I?
Since the application that I was writing was a demonstration of the cool new features of .NET Compact Framework version 3.5, I decided to try my hand a using Language Integrated Query, specifically LINQ to Objects. The resulting code was small, worked well and was quite easy to read. Let's take a look at what I wrote.
public static List<ListViewItem> GetCheckedListViewItems(ListView lv){ List<ListViewItem> checkedItems = (from ListViewItem lvi in lv.Items where (true == lvi.Checked) select lvi).ToList(); return checkedItems;}
The method above is based on my Lunch Launcher demo application, as shown during the What's New in .NET Compact Framework version 3.5 session that I delivered at MEDC 2007 last month. How does it work? First, we specify that we are interested in the ListViewItem objects contained within the ListView.Items property.
from ListViewItem lvi in lv.Items
Next, we define the condition under which we are interested in the item, in our case when the item has been checked by the user.
where (true == lvi.Checked)
Then we select the item.
select lvi
Lastly, we call the ToList method to have the selected items returned to us as a List<ListViewItem>.
Pretty neat and much nicer to read than a foreach loop. If you have installed the beta of .NET Compact Framework version 3.5, give LINQ a try and see how it can make your applications easier to write.
Enjoy!
-- DK
[Edit: fix formatting]
Disclaimers:
This posting is provided "AS IS" with no warranties, and confers no rights.
The information contained within this post is in relation to beta software. Any and all details are subject to change.
Comments
- Anonymous
June 18, 2007
As it is a method that is an extension, wouldn't it be even better if it was an Extension Method... So, err: public static List<ListViewItem> GetCheckedItems(this ListView lv) I don't think Extension Properties are supported (yet), otherwise the exact same member could be defined that way and thus any caller code would work on all platforms. In fact the article in the current MSDN Magazine suggests this usage, see http://msdn.microsoft.com/msdnmag/issues/07/07/ShareCode/default.aspx#S13