News | Articles | Libraries | Developer Tools | Books | Forum Links | Search   
Sections:
 

By Alexander Shargin, .
Print version

QA: How to add a lot of items to the ListView control?

Question

I have to add many items to a list view in my program. But the process is VERY slow. How can I speed things up?

Answer

Use virtual list view

The only way to eliminate time used to add items to a list box is not to add them at all. This is possible with virtual list view (i. e. list view with LVS_OWNERDATA style set). Virtual list view does not store information on its items. Instead it stores the number of items in the list. When virtual list view is redrawn it requests only the information on the items actually visible on the screen. To provide this information you must handle LVN_GETDISPINFO notification write data to LV_DISPINFO structure provided to notification handler.

To make your list view virtual follow these steps.

  1. Assign LVS_OWNERDATA style to list view. You can do it in resource editor "Owner data" check box in list view properties) or programmatically (using CWnd::Create or CWnd::ModifyStyle methods).
  2. Set the number of items in the list view. This is done using CListCtrl::SetItemCount method. If the list view is located in dialog, this method is usually called from WN_INITDIALOG handler.
  3. Handle LVN_GETDISPINFO notification. Fill information on requested item in LV_DISPINFO structure. You can use ClassWizard to add LVN_GETDISPINFO handler to your application. Let's assume you want to fill the list with 1000000 items titled "Item X" (X - number of the item). In this case your LVN_GETDISPINFO will look like this.
void CLVTestDlg::OnGetdispinfoList1(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR; int iItem = pDispInfo->item.iItem; if(pDispInfo->item.mask & LVIF_TEXT != 0) { // Item's text is requested. Write it to pDispInfo structure. _stprintf(pDispInfo->item.pszText, _T("Item %d"), iItem); } *pResult = 0; }

Use SetRedraw method

If it's impossible to use virtual list view for some reason, there is not much you can do. Copying item data to list view's internal structures takes time. You can do nothing about it. But you can eliminate time used to redraw the list view over and over again after each item is added. To do this call CListCtrl::SetRedraw method to turn off list redrawing, then add all items to the list and use CListCtrl::SetRedraw method again, e. g.:

extern CListCtrl list; list.SetRedraw(FALSE); // turn the drawing offf // add items to the list list.SetRedraw(TRUE); // turn the drawing on again

This approach can speed up your program 2-4 times but do not expect much if the number of items is really big.

Discuss

Discuss this article. Here you can write your comments and read comments of other developers.
Rate this article:     Poor Excellent    
 12345 
© 2001-2005 Pocket PC Developer Network, a division of Spb Software House