How to store Listview items in a list?

B M-A 361 Reputation points
2023-06-03T03:19:22.7633333+00:00

Hello,

I want to store all listview items in a list, or to convert in a table, but I get unable to cast error.

I tried using for each :

foreach ( var item in ListView.Items)
                    {
                        list.ListItems.Add(item);
                    }

Best regards,

Developer technologies Windows Presentation Foundation
Developer technologies C#
{count} votes

Accepted answer
  1. don bradman 621 Reputation points
    2023-06-03T04:02:39.4066667+00:00

    Is list a List<string> ? and are the items in your ListView of type ListViewItem ?

    If so then try,

    List<string> list = new List<string>();
    
    foreach (ListViewItem item in ListView.Items)
    {
        list.Add(item.ToString());
    }
    

    Since you are getting an "unable to cast" error, it may be because the items in your ListView are not of type ListViewItem. In that case, you can try using the ItemsSource property of the ListView to get the data source of the ListView and cast it to the appropriate type like below

    List<Person> personList = new List<Person>();
    
    foreach (Person person in ListView.ItemsSource)
    {
        personList.Add(person);
    }
    

1 additional answer

Sort by: Most helpful
  1. Vu Le 20 Reputation points
    2023-06-03T03:37:33.1633333+00:00

    You should provide more context such as the platform you're working on. The code context such as what type of the list ,ListViewobject, how it's declared.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.