How to implement a basic virtual ListView in C#?

 

Virtual list views, also known as owner data, appear to the user as any other list view but the underlying code to populate them is optimized for large data sets. A virtual list-view control maintains very little item state information itself. List views that contain more than several hundred items generally achieve significant performance improvement as virtual lists.

The decision to use a virtual list view should be based on the cost of fetching the data as well as the volume of data. In the case of a remote database query with a huge result set a virtual list view would be an obvious choice.

When a ListView object is in virtual mode, it creates ListViewItem objects dynamically instead of using the Items collection. This event is raised when the object must create a ListViewItem object. A handler for this event should create the appropriate ListViewItem or retrieve it from the cache, and pass it back by way of the Item property.

The best example for Virtual List view is Windows Explorer. There might be thousands of files in a folder. All these file information will not be added at once. Mostly the explorer provides information only for the visible items.

When we implement a virtual list controls, we will not add the items to the list view. Instead, we will set only the number of elements in the listview. A callback will be issued by the control when it requires to display a specific item.

How to enable a Virtual Mode for List View?

listView1.VirtualMode = true;
listView1.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(listView1_RetrieveVirtualItem);

How to provide ListViewItem

You an see that we’ve added a event handler for retrieving the virtual items. Just implement the callback and provide the ListViewItem info.

void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
    e.Item = new ListViewItem();
    e.Item.Text = bornInfo[e.ItemIndex].Title;
    e.Item.BackColor = Color.YellowGreen;
    e.Item.Font = new Font("Consolas", 11);
    e.Item.SubItems.Add( bornInfo[e.ItemIndex].Description);
}

How to set the number of items in the list view?

// Set the count
listView1.VirtualListSize = bornInfo.Count;

A complete sample to retrieve Born On This Day Info from IMDB

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace VirtualListControlDemo
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Enable Virtual List mode
            listView1.VirtualMode = true;
            listView1.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(listView1_RetrieveVirtualItem);
            listView1.View = View.Details;
            listView1.Columns.Add("Person", 150 );
            listView1.Columns.Add("Description", 400);
        }

        // Draw the item
        void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            e.Item = new ListViewItem();
            e.Item.Text = bornInfo[e.ItemIndex].Title;
            e.Item.BackColor = Color.YellowGreen;
            e.Item.Font = new Font("Consolas", 11);
            e.Item.SubItems.Add( bornInfo[e.ItemIndex].Description);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Load the XML document
            XDocument xmlDoc = XDocument.Load("http://rss.imdb.com/daily/born/");
            // Parse the required info
            bornInfo = (List<BornOnThisDay>)(from item in xmlDoc.Descendants("item")
                select new BornOnThisDay
                {
                    Title = item.Element( "title").Value,
                    Description = item.Element("description").Value
                }).ToList();

            // Set the count
            listView1.VirtualListSize = bornInfo.Count;
        }

        List<BornOnThisDay> bornInfo = new List<BornOnThisDay>();
    }
    public class BornOnThisDay
    {
        public string Title;
        public string Description;
    }
}
 

Learning Django: 02 – Creating the main page

 
Django is an MVC (Model-View-Controller) framework. Model contains the data where the website is operating, view is the presentation module and controller encapsulates the business logic.

Hope you’ve done with the Setting up Django and Python.

$ python manage.py startapp sampleview

This will create a folder named sampleview in your project folder which contains the following files generate.

__init__.py – tells python that this is a module
views.py – contains the code for the view
models.py – contains the data models

Modifying Views.py

# Create your views here.
from django.http import HttpResponse
def main_page(request) :
	output = u'''
		<html>
			<head><Title>%s</Title></head>
			<body>
				<h1>%s</h1><p>%s</p>
			</body>
		</html>
	''' % (
	u'02-Learning Django',
	u'Setting up main page',
	u'Now you learned how to setup a view and page with Django!'
	)
	return HttpResponse(output)

The code is simple and straight forward. Those who worked with C printf function can catch up this thing easily.
1. Defined a function called main_page (this can be any name)
2. Defined a variable called output with a text formatting the %s definitions are place holders and it’s values will be generated dynamicaly.
3. Make sure that you properly indent the code to avoid error while loading the webpage. The code must be aligned according to the function definition
4. The strings which start with “u” tells that it’s unicode string. Finally return the the output as HttpResponse. This function will be called from urls.py on loading the page.

Modifying urls.py

The execution of the webpage start from url.py. Once after we define the views, it’s necessary to connect the url to the view.  First we’ve to import views to get the main_page function defined inside it. Keep the default imports in the first line unchanged

from django.conf.urls.defaults import *
from bookmarks.views import *

urlpatterns = patterns('',
     (r'^$', main_page ),
)

We’re using regular expressions here to generate the URL. It doesn’t make much sense with this simple content generation. To know more about the strings used here, please find regular expressions documentation under python

Now you’re done. Load the page http://localhost:8000 to see the effect.