Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using loops to get at each item in a ListView?

What is a nice and effective way of getting at each item in a ListView of more than one column using loops?

After doing a fair bit of digging around I couldn't really find anything so I when I did find something I wanted to share it on here see if people have better ways of doing it. Also sort of like preempting a question that is bound to come up as I was scratching my head for a bit thinking how do ??? eerrrr .... I ?

I like this website so I wanted to share my solution to the question above. Sort of backwards I know but still, I know it will help someone out somwhere. = )

    private ArrayList getItemsFromListViewControl()
    {                      
        ArrayList lviItemsArrayList = new ArrayList();

        foreach (ListViewItem itemRow in this.loggerlistView.Items)
        {
            //lviItemsArrayList.Add(itemRow.Text); <-- Already included in SubItems so ... = )

            for (int i = 0; i < itemRow.SubItems.Count; i++)
            {
                lviItemsArrayList.Add(itemRow.SubItems[i].Text);
                // Do something useful here, for example the line above.
            }
        }
        return lviItemsArrayList;
    }

This returns a linear array based representation of all the items belong to a targeted ListView Control in an ArrayList collection object.

like image 405
IbrarMumtaz Avatar asked Aug 27 '09 21:08

IbrarMumtaz


2 Answers

I suggest using IEnumerable as the return type of the method and using "yield return" to return each subitems.

private IEnumerable<ListViewSubItem> GetItemsFromListViewControl()
{                      
    foreach (ListViewItem itemRow in this.loggerlistView.Items)
    {            
        for (int i = 0; i < itemRow.SubItems.Count; i++)
        {
            yield return itemRow.SubItems[i]);
        }
    }
}

although if you are using .NET 3.5 I suggest using LINQ too.

like image 102
mrtaikandi Avatar answered Nov 10 '22 23:11

mrtaikandi


    foreach (ListViewItem itemRow in this.ListView.Items)
    {            
        for (int i = 0; i < itemRow.SubItems.Count; i++)
        {
            // Do something useful here !
            // e.g 'itemRow.SubItems[count]' <-- Should give you direct access to
            // the item located at co-ordinates(0,0). Once you got it, do something 
            // with it.
        }
    }

Thats my way of doing it.

like image 31
IbrarMumtaz Avatar answered Nov 10 '22 21:11

IbrarMumtaz