简体   繁体   中英

Loop through all elements in a ListView in virtual mode

I have a reporting module which creates PDF reports from ListViews.

Now, I have a ListView in Virtual mode and therefore I cannot loop over the Items collection.

How do I loop over all elements in the list view from the reporting module?

I can get the VirtualListSize property, so I know how many elements there are in the list. Could I somehow call the RetreiveVirtualItem explicitly?

The Reporting module has no knowledge about the underlaying list in the ListView.

So, a listview in virtual mode is just a visualization of your underlying list, correct?

Perhaps report should be getting the data from the underlying list instead of the virtual list view.

In a virtual ListView, you cannot iterate the Items , but you can still access them by their index:

for (int i = 0; i <  theVirtualListView.VirtualListSize; i++) {
    this.DoSomething(theVirtualListView.Items[i]);
}

The best solution I came up with is to have a delegate in the report class where a pass on the same delegate as I set on the ListView.RetrieveVirtualItem.

class Report {
   [...]
   // Called when the content of an VirtualItem is needed.
   public event RetrieveVirtualItemEventHandler RetrieveVirtualItem;
   [...]

   private AddRows() {
      for (int i = 0; i < GetItemCount(); i++) 
         AddRow(GetItem(i));
   }

   private ListViewItem GetItem(n) {
      if (_listView.VirtualMode)
         return GetVirtualItem(n);
      return _listView.Items[n];
   }

    private ListViewItem GetVirtualItem(int n)
    {
        if (RetrieveVirtualItem == null)
            throw new InvalidOperationException(
                "Delegate RetrieveVirtualItem not set when using ListView in virtual mode");

        RetrieveVirtualItemEventArgs e = new RetrieveVirtualItemEventArgs(n);
        RetrieveVirtualItem(_listView, e);
        if (e.Item != null)
        {
            return e.Item;
        }
        throw new ArgumentOutOfRangeException("n", "Not in list");
    }

   private static int GetItemsCount()
   {
      if (_listView.VirtualMode)
          return _listView.VirtualListSize;
      return _listView.Items.Count;
   }
}

You can always expose the underlying list to the outside world:

foreach (object o in virtListView.UnderlyingList)
{
  reportModule.DoYourThing(o);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM