ListView SelectedIndexChanged trouble getting SelectedItems

Posted on 2006-06-03
Last Modified: 2007-12-19

I'm handleing the correct event when the user changes the selected item, but when I go and try to get that item, I'm getting null.  I use

private ListViewItem GetSelection( ListView listView )
    foreach ( ListViewItem listViewItem in listView.SelectedItems )
        return listViewItem;
    return null;

to get the one and on y choice in my single selection ListView.  I know there's a better way to do this, and if you have it I'd love to see it.  But the problem is that there the foreach does not get entered into, even thoiugh I only call this function when the user has selected an item in the ListView.  Can anybody suggest a solution?

Question by:ba272
    LVL 11

    Accepted Solution

    why dont you make something like this:

    internal ListViewItem _selectedItem; //<-- classmember field
    //eventhandler for your listviews
    private void ListViewSelectedIndexChanged(object sender, EventArgs e)
      ListView listView = sender as ListView;
      this._selectedItem = (listView.SelectedItems.Count > 0 ? listView.SelectedItems[0] : null);

    _selectedItem is null or the selected listviewitem.

    Author Comment

    thanks. works great.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
    In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    732 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now