Home > Articles > Programming > Windows Programming

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020