Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Displaying Computed Data in Virtual Mode

Another scenario where you may want to take explicit control over providing a display value for each cell is when you are working with data that contains computed values, especially in combination with bound data and large sets of data. For example, you may need to present a collection of data that has tens of thousands or even millions of rows in a grid. You really ought to question the use case first before supporting such a thing, but if you really need to do this, you probably don’t want to clobber your system’s memory by creating multiple copies of that data. You may not even want to bring it all into memory at one time, especially if this data is being dynamically created or computed. However, you will want users to able be to smoothly scroll through all that data to locate the items of interest.

Virtual mode for the DataGridView lets you display values for cells as they are rendered, so that data doesn’t have to be held in memory when it’s not being used. With virtual mode you can specify which columns the grid contains at design time, and then provide the cell values as needed, so they display at runtime but not before. The grid will internally only maintain the cell values for the cells that are displayed; you provide the cell value on an as-needed basis.

When you choose to use virtual mode, you can either provide all of the row values through virtual mode event handling, or you can mix the columns of the grid with data-bound and unbound columns. You have to define the columns that will be populated through virtual mode as described earlier in the “Programmatic DataGridView Construction” section. If you also data bind some columns, then the rows will be populated through data binding and you just handle the events necessary for virtual mode for the columns that aren’t data bound. If you aren’t data binding, you have to add as many rows as you expect to present in the grid, so the grid knows to scale the scrollbar appropriately. You then need a way to get the values corresponding to virtual mode columns when they are needed for presentation. You can do this by computing the values dynamically when they are needed, which is one of the main times that you would use virtual mode. You might also use cached client-side data in the form of an object collection or data set, or you might actually make round-trips to the server to get the data as needed. With the latter approach, you’ll need a smart preload and caching strategy, because you could quickly bog down the application if data queries have to run between the client and the server while the user is scrolling. If the data being displayed is computed data, then it really makes sense to wait to compute values until they are actually going to be displayed.

Setting Up Virtual Mode

The following steps describe how to set up virtual mode data binding.

  1. Create a grid and define the columns in it that will use virtual mode.
  2. Put the grid into virtual mode by setting the VirtualMode property to true.
  3. If you aren’t using data binding, add as many rows to the grid as you want to support scrolling through. The easiest and fastest way to do this is to create one prototype row, then use the AddCopies method of the Rows collection to add as many copies of that prototype row as you would like. You don’t have to worry about the cell contents at this point, because you are going to provide those dynamically through an event handler as the grid is rendered.
  4. The final step is to wire up an event handler for the CellValueNeeded event on the grid. This event will only be fired when the grid is operating in virtual mode, and will be fired for each unbound column cell that is currently visible in the grid when it is first displayed and as the user scrolls.

The code in Listing 6.2 shows a simple Windows Forms application that demonstrates the use of virtual mode. A DataGridView object was added to the form through the designer and named m_Grid, and a button added to the form for checking how many rows had been visited when scrolling named m_GetVisitedCountButton.

Example 6.2. Virtual Mode Sample

partial class VirtualModeForm : Form
{
   private List<DataObject> m_Data = new List<DataObject>();
   private List<bool> m_Visited = new List<bool>();
   public VirtualModeForm()
   {
      InitializeComponent();
      m_Grid.CellValueNeeded += OnCellValueNeeded;
      m_GetVisitedCountButton.Click += OnGetVisitedCount;
      InitData();
      InitGrid();
   }

   private void InitData()
   {

       for (int i = 0; i < 1000001; i++)
       {

          m_Visited.Add(false);
          DataObject obj = new DataObject();
          obj.Id = i;
          obj.Val = 2 * i;
          m_Data.Add(obj);
       }
   }

   private void InitGrid()
   {

      m_Grid.VirtualMode = true;
      m_Grid.ReadOnly = true;
      m_Grid.AllowUserToAddRows = false;
      m_Grid.AllowUserToDeleteRows = false;
      m_Grid.ColumnCount = 3;
      m_Grid.Rows.Add();
      m_Grid.Rows.AddCopies(0, 1000000);
    // Uncomment the next line and comment out the
    // the rest of the method to switch to data bound mode
    //    m_Grid.DataSource = m_Data;
   }
   private void OnCellValueNeeded(object sender,
      DataGridViewCellValueEventArgs e)
   {
      m_Visited[e.RowIndex] = true;
      if (e.ColumnIndex == 0)
      {

         e.Value = m_Data[e.RowIndex].Id;
      }
      else if (e.ColumnIndex == 1)
      {         e.Value = m_Data[e.RowIndex].Val;
      }
      else if (e.ColumnIndex == 2)
      {
         Random rand = new Random();
         e.Value = rand.Next();
      }
   }

   private void OnGetVisitedCount(object sender, EventArgs e)
   {
      int count = 0;
      foreach (bool b in m_Visited)
      {
         if (b) count++;
      }
      MessageBox.Show(count.ToString());
   }
}
public class DataObject
{

   private int m_Id;
   private int m_Val;

   public int Val
   {
      get { return m_Val; }
      set { m_Val = value; }
   }

   public int Id
   {
      get { return m_Id; }
      set { m_Id = value; }
   }
}

The form constructor starts by calling InitializeComponent as usual, to invoke the code written by the designer from drag-and-drop operations and Properties window settings. For this sample, that just declares and creates the grid and the button controls on the form. The constructor code then subscribes two event handlers using delegate inference.

The first event handler is the important one for virtual mode—the CellValueNeeded event. As mentioned earlier, this event is only fired when the grid is in virtual mode and is called for each unbound column cell that is visible in the grid at any given time. As the user scrolls, this event fires again for each cell that is revealed through the scrolling operation. The constructor also subscribes a handler for the button click, which lets you see how many rows the CellValueNeeded event handler was actually called for.

After that, the constructor calls the InitData helper method, which creates a collection of data using a List<T> generic collection that contains instances of a simple DataObject class, defined at the end of Listing 6.2. The DataObject class has two integer values, Id and Val, which are presented in the grid. The collection is populated by the InitData helper method with one million rows. The Id property of each object is set to its index in the collection, and the Val property is set to two times that index.

Initializing the Grid

After the data is initialized, the constructor calls the InitGrid helper method, which does the following:

  • Sets the grid into virtual mode.
  • Turns off editing, adding, and deleting.
  • Adds three text box columns to the grid by setting the ColumnCount property.
  • Adds one row to the grid as a template.
  • Uses the AddCopies method on the Rows collection to add one million more rows. This method also contains a commented-out line of code that can be used to change the VirtualMode download sample to be data bound against the object collection so that you can see the difference in load time and memory footprint.

After that, Windows Forms event handling takes over for the rest of the application lifecycle. Because the grid was set to virtual mode, the next thing that happens is the OnCellValueNeeded handler will start to get called for each cell that is currently displayed in the grid. This method is coded to extract the appropriate value from the data collection based on the row index and column index of the cell that is being rendered for the first two columns. For the third column, it actually computes the value of the cell on the fly, using the Random class to generate random numbers. It also sets a flag in the m_Visited collection—you can use this to see how many rows are actually being rendered when users scroll around with the application running.

Understanding Virtual Mode Behavior

If you run the VirtualMode sample application from Listing 6.2, note that as you run the mouse over the third column in the grid, the random numbers in the cells that the mouse passes over change. This happens because the CellValueNeeded event handler is called every time the cell paints, not just when it first comes into the scrolling region, and the Random class uses the current time as a seed value for computing the next random number. So if the values that will be calculated when CellValueNeeded are time variant, you will probably want to develop a smarter strategy for computing those values and caching them to avoid exposing changing values in a grid just because the mouse passes over them.

The OnGetVisitedCount button Click handler displays a dialog that shows the number of rows rendered based on the m_Visited collection. If you run the VirtualMode sample application, you can see several things worth noting about virtual mode. The first is that the biggest impact to runtime is the loading and caching of the large data collection on the client side. As a result, this is the kind of operation you would probably want to consider doing on a separate thread in a real application to avoid tying up the UI while the data loads. Using a BackgroundWorker component would be a good choice for this kind of operation.

When dealing with very large data sets, if the user drags the scrollbar thumb control, a large numbers of rows are actually skipped through the paging mechanisms and latency of the scroll bar. As a result, you only have to supply a tiny percentage of the actual cell values unless the user does an extensive amount of scrolling in the grid. This is why virtual mode is particularly nice for computed values: you can avoid computing cell values that won’t be displayed.

If you run this example and scroll around for a bit, then click the Get Visited Count button, you will see how many rows were actually loaded. For example, I ran this application and scrolled through the data from top to bottom fairly slowly several times. While doing so, I saw smooth scrolling performance that looked like I was actually scrolling through the millions of rows represented by the grid. However, in reality, only about 1,000 rows were actually rendered while I was scrolling.

What if you want to support editing of the values directly in the grid? Maybe you are just using virtual mode to present a computed column with a relatively small set of data, and you want to use that column’s edited value to perform some other computation or store the edited value. Another event, CellValuePushed, is fired after an edit is complete on a cell in a virtual mode grid. If the grid doesn’t have ReadOnly set to true, and the cells are of a type that supports editing (like a text box column), then the user can click in a cell, hesitate, then click again to put the cell into editing mode. After the user has changed the value and the focus changes to another cell or control through mouse or keyboard action, the CellValuePushed event will be fired for that cell. In an event handler for that event, you can collect the new value from the cell and do whatever is appropriate with it, such as write it back into your data cache or data store.

Virtual Mode Summary

That’s all there is to virtual mode: Set the VirtualMode property to true, create the columns and rows you want the grid to have, and then supply a handler for the CellValueNeeded event that sets the appropriate value for the cell being rendered. If you need to support the editing of values directly in the grid, then also handle the CellValuePushed event and do whatever is appropriate with the modified values as the user makes the changes. Hopefully, you won’t need to use virtual mode often in your applications, but it’s nice to have for presenting very large data collections or computing column values on the fly. There are no hard and fast rules on when virtual mode will be needed. If you are having scrolling performance problems in your application, or you want to avoid the memory impact of holding computed values for large numbers of rows in memory, you can see if virtual mode solves your problems. You will still need to think about your data retrieval and caching strategy, though, to avoid seriously hampering the performance of your application on the client machine.

  • + Share This
  • 🔖 Save To Your Account