Desktop Applications Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/winforms/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Tue, 19 Nov 2013 23:48:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 https://www.anujvarma.com/wp-content/uploads/anujtech.png Desktop Applications Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/winforms/ 32 32 Windows DataGridView – Improving the Data Display (Refresh) Performance https://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance-2/ https://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance-2/#comments Fri, 09 Mar 2012 18:56:22 +0000 http://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance-2/   The DataGridView is used everywhere – both in ASP.net apps as well as WinForms apps. A quick google search will reveal the scale of users affected by the slow […]

The post Windows DataGridView – Improving the Data Display (Refresh) Performance appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
  The DataGridView is used everywhere – both in ASP.net apps as well as WinForms apps. A quick google search will reveal the scale of users affected by the slow refresh rate on the DataGridView control.  How the data is displayed is dictated by a property called the Display Mode. The Display Mode that most datagridview users opt for is the Bound mode.

An object-bound datagridview

Object binding refers to the ability to bind a control to a custom data type (your domain objects). In pre-object binding days, one would bind a control directly to the raw data (e.g. an int CustomerID and a string CustomerName retrieved from the datasource). This was a cumbersome approach since most of the data could logically be grouped into custom data types (e.g. Customer). The User Interface was mainly interested in displaying the domain types (e.g. Customer) and less interested in native data types such as ints and strings. This led to the development of object-binding as an alternative to older raw data-binding.

A typical datagridview application that uses object binding will involve the following steps:

  1. Fetching Data (usually using ADO.NET and a DataReader/DataTable/DataSet combination).
  2. Storing the fetched data in a local collection (typically an IList<T> where T represents your custom domain object e.g. IList<Customer>).
  3. Converting the IList<Customer> to a BindingList<Customer>
  4. Binding the BindingList to the datagridview

For a detailed walkthrough of custom object binding to a datagridview, see this MSDN magazine article.

Bound Display Mode

For object bound DGVs (datagridviews), the ‘Bound’ mode is the most commonly used display mode. In this mode, the datagridview control is automatically bound to the source of the data – and any changes to the source of the data cause refreshes of the various UI elements of the grid (columns, rows etc.). This offers a degree of convenience that is appealing, at least for small volumes of data. This Bound mode kicks into effect whenever you set the Datasource property on the  datagridview as shown in the snippet below.

Code Snippet
  1. // Define your BindingList
  2.           BindingList<object> bindableDataSource = new BindingList<object>();
  3.  
  4.           // Add some data to the bindingList
  5.           BindingList<object> list = CreateData();
  6.           foreach (object item in list)
  7.           {
  8.               bindableDataSource.Add(item);
  9.           }
  10.           // This actually ‘binds’ the gridview to the BindingList. Any changes to the BindingList from here on affect the gridview.
  11.           // For e.g. – The ‘bound’ gridview would refresh its layout every time a new item is added to this BindingList
  12.           dataGridView1.DataSource = bindableDataSource;

The Problem with Bound display mode

The first indications of problems with the bound mode are visible as soon as you start adding additional items to the source list (while the grid is bound to it). Note that it is possible to add additional items without binding the grid – and then performing the binding step at the very end – as shown in the snippet above. However, even with this approach, at some point, you may need to add/delete items from the source list – causing unnecessary refreshes. More serious problems with the DataGridView start manifesting themselves as the size of the bound collection grows. For larger sets of data, this problem grows to unacceptable response times.

Enter Virtual Mode

By default, most datagridview developers use a Display mode called Bound. In this display mode, the data in the grid is automatically bound to the data in the datasource. This means that the grid view control handles all aspects of fetching the data as well as displaying the data. While this offers convenience, it is the main reason for slower display performance on the DGV. Fortunately, there is another display mode available to address this problem. This mode is known as the virtual display mode. In this display mode, instead of being bound to the entire datasource, the grid is essentially bound to a small subset (a cached portion) of the datasource. This small subset is the set of data should match the data that is visible on the grid (the exact amount of data is under the programmer’s control). Whenever a user wants to see more data (scrolls the grid), that data is fetched from the datasource, placed into cache – and returned to the grid from the cache. This way, only a small amount of data is ever bound to the grid – and even that only through a memory based cache.  This alleviates a lot of issues with the Windows DataGridView – including slow UI refreshes, locked UIs etc.

Quick Conversion from bound to virtual (full source code at the end of this post)

In your source code, if you are using the bound display mode (happens by default if you set the ‘datasource property) you will be setting the datasource property on your gridview somewhere – e.g.

Code Snippet
  1. this.dataGridView1.DataSource = _customers;

Instead of setting this datasource property, what you will need to do is initialize the grid to use virtual mode. This is shown in the snippet below (full source code included at the end of this post).

Code Snippet
  1. private void InitializeGrid()
  2.         {
  3.             // Enable virtual mode.
  4.             this.dataGridView1.VirtualMode = true;
  5.  
  6.             // Connect the virtual-mode events to event handlers.
  7.             this.dataGridView1.CellValueNeeded += new
  8.                 DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);

The actual dataGridView1_CellValueNeeded event is where the event to request more data is handled.  The included source code below provides a quick implementation of the virtual display mode – which should work for simple use cases. For a full walkthrough on a virtual mode implementation, see MSDN.

What if the Virtual Mode is still sluggish?

If the performance of virtual mode is still sluggish for your data (if you have several thousands of rows of data), chances are you need to look elsewhere. There are several 3rd party grid controls on the market – including Infragistics, Syncfusion and Telerik. One such grid that I have worked with extensively is Syncfusion’s Grid Control. On my project, we were handling several hundred MBs of data in the grid – with refreshes occurring in real-time or near real-time (i.e. no sluggishness).  A performance comparison is detailed in an earlier post.

In addition to the speed, you also get a host of features that I like to call Grid on Steroids features. These include nested grids (which make it possible to efficiently display hierarchical data), multiple column sorts (which isn’t available out of the box in Windows DataGridView – but can be custom built), pivot tables and more.

Summary

If you are witnessing slow rendering (sluggish rendering) of your datagridview in your WinForms (or ASP.NET ) application, chances are you are using automatic binding (bound display mode). Chances are that you will experience a significant benefit from trying the virtual display mode built into the gridview. This display mode binds to a smaller, cached subset of the full data, allowing quicker UI refreshes. The sample attached here shows a grid using the bound mode and another grid using virtual mode (both with identical 10000 rows of customer data). Even with this simple sample of a few 100 KBs of data, a noticeable difference can be seen (by visual inspection) when one tries to scroll down the grid to view more rows. The refresh rate of the virtual mode grid clearly wins out.  If you find the virtual mode also insufficient for your application’s volume of data, you might need something like the syncfusion grid.

Source Code

Download Full Solution

About the Author

  Anuj Varma is a Microsoft .NET architect specializing in high-performance applications. His specific expertise in the .NET framework architecture as well as 3rd party controls (such as Syncfusion) built around the framework,  makes him a sought after performance expert for .NET applications. Most recently, he has worked on an ASP.NET revamp of dell.com as well as a WinForms app used to map Ocean floors (Petrel). Both these applications were built with performance (UI performance as well as Data Access Layer performance) as a key driver. In addition to n-Tier apps, Anuj works hands-on in the WCF and Azure arena to bring performance to existing SOA apps. Anuj’s personal blog can be found here – anujvarma.com/blog/technology,

The post Windows DataGridView – Improving the Data Display (Refresh) Performance appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance-2/feed/ 3
WinForms and Advanced UI Programming in .NET, Anuj Varma https://www.anujvarma.com/winforms-and-advanced-ui-programming-in-net-anuj-varma/ https://www.anujvarma.com/winforms-and-advanced-ui-programming-in-net-anuj-varma/#respond Thu, 01 Dec 2011 21:28:00 +0000 http://www.anujvarma.com/?p=1347 3rd Party UI Libraries: Advanced UI Controls including 3rd party datagrids, list controls, tabbed layouts etc. may be required to meet the needs of today’s enterprise data. Syncfusion and Infragistics […]

The post WinForms and Advanced UI Programming in .NET, Anuj Varma appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
  • 3rd Party UI Libraries: Advanced UI Controls including 3rd party datagrids, list controls, tabbed layouts etc. may be required to meet the needs of today’s enterprise data. Syncfusion and Infragistics are among 3rd party UI controls that I have been able to work with extensively on behalf of my clients.
  • Datagrids: Customized datagrids for handling heirarchical data, grouping and sorting of large volumes of data. Sophisticated datagrid (syncfusion) that accepts a variety of data feeds, supports cell-level updates, advanced grouping options, custom formatting, grid export to various formats, in-grid calculations (excel like) and other advanced grid capabilities. If your application handles large volumes of data and needs to display them efficiently, contact me to see if I can help.
  • Multiple application UI Support: Complete decoupling of business model and UI: Most MVC implementations accomplish decoupling upto a certain point – but still tie the application to a particular type of interface (e.g. web or desktop). A truly decoupled design creates a Model layer which can exportto any type of UI – web, desktop, mobile etc. If your application is in need of multiple UI display types (web, mobile devices, desktop), my UI experience may be valuable.
  • Unit Testing UI Components: Typically, writing unit tests for UI components has been a challenging task. With advances in tools such as NUnitForms and Cassini (simple http server), it is possible to automate unit testing of UI components. Contact me to see how I can help write an automated test suite for your application.
  • Overall Framework design: For those applications looking for a standardized approach to all their applications (standardized logging, exception handling, UI controls data-binding etc.), a well designed application framework can go a long way. With the help of advanced patterns usage coupled with enterprise components (such as Enterprise Application Blocks, SmartClient Software Factory SCSF), some of my experience with frameworks can help you build a corporate-wide application framework.
  • The post WinForms and Advanced UI Programming in .NET, Anuj Varma appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

    ]]>
    https://www.anujvarma.com/winforms-and-advanced-ui-programming-in-net-anuj-varma/feed/ 0
    Superfast display (loading) of data into your UI (WinForms, MVC or ASP.NET) https://www.anujvarma.com/superfast-rendering-of-ui-data-in-winforms-world-2-2/ https://www.anujvarma.com/superfast-rendering-of-ui-data-in-winforms-world-2-2/#respond Sat, 19 Nov 2011 10:12:54 +0000 http://www.anujvarma.com/superfast-rendering-of-ui-data-in-winforms-world-2-2/ While this post compares the WinForms datagridview with a 3rd party (syncfusion) Grid Control for windows, the same comparison also applies to grid controls in the MVC and ASP.NET webforms […]

    The post Superfast display (loading) of data into your UI (WinForms, MVC or ASP.NET) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

    ]]>
    v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);}

    While this post compares the WinForms datagridview with a 3rd party (syncfusion) Grid Control for windows, the same comparison also applies to grid controls in the MVC and ASP.NET webforms world. The same set of 3rd party controls (discussed in this post) are available in each of those environments.

    aspdotnet_grid 

    Business Data and Grids

    Business data tends to organize itself into rows and columns (witness the success of Lotus123, Excel and other spreadsheet software).

    Windows DataGridView

    For the .NET UI developer, the Windows DataGridView is indispensible in that it provides a quick way to organize business data into rows and columns. Sorting, Paging etc. are usually either built in or fairly straightforward to implement. Going beyond the basic sorting (e.g. multiple column sort) or basic grouping (e.g. multiple column groups) calls for some serious investment in time. More importantly, as we shall see in this post, going beyond just a few 100 KBs of bound data, leads to serious performance degradation – making the DataGridView unsuitable for enterprise level grid/tabular data applications.

    Object Binding

    Object binding refers to the ability to bind a control to a custom data type (your domain objects). In pre-object binding days, one would bind a control directly to the raw data (e.g. an int CustomerID and a string CustomerName retrieved from the datasource). This was a cumbersome approach since most of the data could logically be grouped into custom data types (e.g. Customer). The User Interface was mainly interested in displaying the domain types (e.g. Customer) and less interested in native data types such as ints and strings. This led to the development of object-binding as an alternative to older raw data-binding.

    A typical datagridview application that uses object binding will involve the following steps:

    1. Fetching Data (usually using ADO.NET and a DataReader/DataTable/DataSet combination).
    2. Storing the fetched data in a local collection (typically an IList<T> where T represents your custom domain object e.g. IList<Customer>).
    3. Converting the IList<Customer> to a BindingList<Customer>
    4. Binding the BindingList to the datagridview

    For a detailed walkthrough of custom object binding to a datagridview, see this MSDN magazine article.

    Bound versus Virtual Display Modes

    By default, most datagridview developers use a Display mode called Bound. In this display mode, the data in the grid is automatically bound to the data in the datasource.

    This means that the grid view control handles all aspects of fetching the data as well as displaying the data. While this offers convenience, it is the main reason for slower display performance on the DGV.

    Fortunately, there is another display mode available to address this problem.

    This mode is known as the virtual display mode. In this display mode, instead of being bound to the entire datasource, the grid is essentially bound to a small subset (a cached portion) of the datasource. This small subset is the set of data should match the data that is visible on the grid (the exact amount of data is under the programmer’s control). Whenever a user wants to see more data (scrolls the grid), that data is fetched from the datasource, placed into cache – and returned to the grid from the cache. This way, only a small amount of data is ever bound to the grid – and even that only through a memory based cache.  This alleviates a lot of issues with the Windows DataGridView – including slow UI refreshes, locked UIs etc.

    Windows DataGridView’s Virtual Display Mode

    While the DataGridView control is flexible enough to display any IList as its datasource, it starts running into some performance problems for large volumes of data.

    The Virtual mode in the Windows DataGridView control was designed for just such a purpose – to handle refreshes of large volumes of data. It does this by postponing the rendering of the entire data all at once – and only renders a fixed number of rows and columns at a time. As one tries to scroll down (or up), new data is rendered at that very instant – using predefined events (CellValueNeeded event in the DataGridView).

    // Enable virtual mode on windows datagridview

    this.dataGridView1.VirtualMode = true;

     

    // Connect the virtual-mode events (scrolling on the datagridview) to event handlers. 

    this.dataGridView1.CellValueNeeded += new DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);

    For even larger volumes of data..

      While the virtual display mode in the DataGridView offers an option to display lots of data without slowing down refresh rates, even this powerful mode starts showing sluggishness for larger amounts of data (several hundred MBs of data).

    What is one to do if one needs to continue displaying data in a grid – and the underlying datasource consists of several hundred(s) MBs of data?

    Enter Syncfusion

      Syncfusion is a 3rd Party UI library – which contains several advanced controls in its toolbox. It offers a GridControl with all the basic grid display capabilities.

    In addition to the basic gridcontrol,  it offers something called a GridGroupingControl – which is a GridControl on steroids.

    (NOTE: The difference between the GridGroupingControl and the GridControl in Syncfusion is basically in the set of features – the GridGroupingControl has a richer set of features. Performance-wise, they are both comparable).

    The rest of this post summarizes some of my initial experiences as a Syncfusion developer – both in terms of performance as well as built-in capabilities.

    Syncfusion Grid Grouping Control Features:  Grouping by Multiple Columns, Nested Grids (Hierarchical data)

    NestedTableHierarchy_larger


    1. Grouping by multiple columns

      If one is interested in grouping by not one – but multiple columns, the grouping grid does it with just a couple of lines of code.


    2. Nested grids

      (to display hierarchical data for example), Syncfusion’s GridGroupingControl provides that out of the box as well (see screenshot above). Note that one can build the same nested table functionality in the Windows DataGridView (using the example shown here).


    3. Sorting by more than one column

      Syncfusion GridGroupingControl provides this type of sorting out of the box as well (whereas one needs to custom build this in the Windows DataGridView as shown in this article).

     

    Syncfusion Grid Control (and Grid Grouping Control)  – Virtual mode and Performance

      However, the main reason our team chose Syncfusion was simple – performance. Syncfusion provides a GridControl class which also has a virtual mode built in.  The virtual mode in Syncfusion’s GridControl works in a similar fashion to Windows DataGridView – by rendering more rows and columns as the user tries to scroll up or down on the grid. The actual events that Syncfusion uses are QueryCellInfo and QueryRowCount (full source code available at the of this post). The snippet below shows the main events that the gridControl needs to have handled.

    // Enable virtual mode.

    this.dataGridView1.VirtualMode = true;

    // the two relevant events for handling the scroll event on the grid control  

    this.gridControl1.QueryCellInfo += new Syncfusion.Windows.Forms.Grid.GridQueryCellInfoEventHandler(this.gridControl1_QueryCellInfo);

    this.gridControl1.QueryRowCount += new Syncfusion.Windows.Forms.Grid.GridRowColCountEventHandler(this.gridControl1_QueryRowCount);

     

    Sample Experiment – Comparing Display Speeds – DataGridView versus Syncfusion Grid

      The source code (included below) uses a simple ArrayList (of Customer objects) – and lets you experiment with the performance of the DataGridView as the number of objects grows. In the sample code, the list of Customers is set to a size of 10,000. At this size, the performance difference between the Windows DatagridView and Syncfusion’s GridControl are already visible. If you try a larger size list, the differences will be even more evident.

    Fetch Time versus Load Time

    The real test of how fast data is displayed on the grid – is the load time (the time taken to display a set of data). We are less concerned here with the data retrieval (fetch) time (for e.g. – retrieving data from an ADO.NET source) – than with the time it takes to display thousands of rows of data.  When one runs the two grids (WinForms dgv and Syncfusion’s gridcontrol) side by side, for the same set of data (see the sample solution below), one can see by just plain visual inspection, the Windows DataGridView loads (displays) a lot slower than Syncfusion’s GridControl.

    By only loading a small subset of data at a time, the virtual mode eliminates the need to bind to large datasets, thereby providing speedier displays. One doesn’t lose out on the large set of data – since scrolling will fetch as much data as needed – on demand.

    Summary

    This article (based on my experience as a Syncfusion developer) shows a side by side performance experiment of the WinForms DataGridView and Syncfusion’s GridControl. Using each of these grids to display the exact same data (10,000 unique customer data records), one can see the different data loading (displaying) speeds. WinForms’ DataGridView starts deteriorating in performance at just a few hundred KBs of display data – in spite of using its own fastest display mode – the virtual display mode.

     Syncfusion’s GridControl offers a faster (superfast) alternative to the WinForms DataGridView. In addition to speed, the grid control offers sophisticated UI manipulation features such as nested grids (nested tables), pivot tables, multiple column sorts etc. Other vendors (Infragistics, Telerik etc.) offer similar grid controls, however, in our initial performance centric comparisons, syncfusion’s grid control seemed to be a clear winner.

       If your business data is in the tens of hundreds of MBs (as ours was) and needs to be bound to UI controls, chances are you will outgrow the built-in WinForms (and asp.net) controls very quickly. You will need to start looking at 3rd party vendors like Syncfusion and Infragistics to provide you with the UI performance that your application needs.

    Source Code

    Download Source Code (Need to download and install Syncfusion Essential Studio Windows Forms Edition 7.3.X or above) 

    About the Author

      Anuj Varma is a Microsoft .NET architect specializing in high-performance applications. His specific expertise in the .NET framework architecture as well as 3rd party controls (Syncfusion development) built around the framework,  makes him a sought after performance expert for .NET applications.  Anuj’s experience as a Syncfusion developer makes him a sought after Syncfusion and UI expert. He continues to specialize in Syncfusion’s Essential Suite for building sophisticated web and desktop applications. Most recently, he has worked on an ASP.NET revamp of dell.com and several UPSTREAM applications in the oil and gas industry. All these applications were built with performance (UI performance as well as Data Access Layer performance) as a key driver.

    The post Superfast display (loading) of data into your UI (WinForms, MVC or ASP.NET) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

    ]]>
    https://www.anujvarma.com/superfast-rendering-of-ui-data-in-winforms-world-2-2/feed/ 0
    Windows DataGridView – Improving the Data Display (Refresh) Performance https://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance/ https://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance/#comments Sun, 13 Nov 2011 11:47:49 +0000 http://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance/   The DataGridView is used everywhere – both in ASP.net apps as well as WinForms apps. A quick google search will reveal the scale of users affected by the slow […]

    The post Windows DataGridView – Improving the Data Display (Refresh) Performance appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

    ]]>
      The DataGridView is used everywhere – both in ASP.net apps as well as WinForms apps. A quick google search will reveal the scale of users affected by the slow refresh rate on the DataGridView control.  How the data is displayed is dictated by a property called the Display Mode. The Display Mode that most datagridview users opt for is the Bound mode.

    An object-bound datagridview

    Object binding refers to the ability to bind a control to a custom data type (your domain objects). In pre-object binding days, one would bind a control directly to the raw data (e.g. an int CustomerID and a string CustomerName retrieved from the datasource). This was a cumbersome approach since most of the data could logically be grouped into custom data types (e.g. Customer). The User Interface was mainly interested in displaying the domain types (e.g. Customer) and less interested in native data types such as ints and strings. This led to the development of object-binding as an alternative to older raw data-binding.

    A typical datagridview application that uses object binding will involve the following steps:

    1. Fetching Data (usually using ADO.NET and a DataReader/DataTable/DataSet combination).
    2. Storing the fetched data in a local collection (typically an IList<T> where T represents your custom domain object e.g. IList<Customer>).
    3. Converting the IList<Customer> to a BindingList<Customer>
    4. Binding the BindingList to the datagridview

    For a detailed walkthrough of custom object binding to a datagridview, see this MSDN magazine article.

    Bound Display Mode

    For object bound DGVs (datagridviews), the ‘Bound’ mode is the most commonly used display mode. In this mode, the datagridview control is automatically bound to the source of the data – and any changes to the source of the data cause refreshes of the various UI elements of the grid (columns, rows etc.). This offers a degree of convenience that is appealing, at least for small volumes of data. This Bound mode kicks into effect whenever you set the Datasource property on the  datagridview as shown in the snippet below.

    Code Snippet
    1. // Define your BindingList
    2.           BindingList<object> bindableDataSource = new BindingList<object>();
    3.  
    4.           // Add some data to the bindingList
    5.           BindingList<object> list = CreateData();
    6.           foreach (object item in list)
    7.           {
    8.               bindableDataSource.Add(item);
    9.           }
    10.           // This actually 'binds' the gridview to the BindingList. Any changes to the BindingList from here on affect the gridview.
    11.           // For e.g. – The 'bound' gridview would refresh its layout every time a new item is added to this BindingList
    12.           dataGridView1.DataSource = bindableDataSource;

    The Problem with Bound display mode

    The first indications of problems with the bound mode are visible as soon as you start adding additional items to the source list (while the grid is bound to it). Note that it is possible to add additional items without binding the grid – and then performing the binding step at the very end – as shown in the snippet above. However, even with this approach, at some point, you may need to add/delete items from the source list – causing unnecessary refreshes. More serious problems with the DataGridView start manifesting themselves as the size of the bound collection grows. For larger sets of data, this problem grows to unacceptable response times.

    Enter Virtual Mode

    By default, most datagridview developers use a Display mode called Bound. In this display mode, the data in the grid is automatically bound to the data in the datasource. This means that the grid view control handles all aspects of fetching the data as well as displaying the data. While this offers convenience, it is the main reason for slower display performance on the DGV. Fortunately, there is another display mode available to address this problem. This mode is known as the virtual display mode. In this display mode, instead of being bound to the entire datasource, the grid is essentially bound to a small subset (a cached portion) of the datasource. This small subset is the set of data should match the data that is visible on the grid (the exact amount of data is under the programmer’s control). Whenever a user wants to see more data (scrolls the grid), that data is fetched from the datasource, placed into cache – and returned to the grid from the cache. This way, only a small amount of data is ever bound to the grid – and even that only through a memory based cache.  This alleviates a lot of issues with the Windows DataGridView – including slow UI refreshes, locked UIs etc.

    Quick Conversion from bound to virtual (full source code at the end of this post)

    In your source code, if you are using the bound display mode (happens by default if you set the ‘datasource property) you will be setting the datasource property on your gridview somewhere – e.g.

    Code Snippet
    1. this.dataGridView1.DataSource = _customers;

    Instead of setting this datasource property, what you will need to do is initialize the grid to use virtual mode. This is shown in the snippet below (full source code included at the end of this post).

    Code Snippet
    1. private void InitializeGrid()
    2.         {
    3.             // Enable virtual mode.
    4.             this.dataGridView1.VirtualMode = true;
    5.  
    6.             // Connect the virtual-mode events to event handlers.
    7.             this.dataGridView1.CellValueNeeded += new
    8.                 DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);

    The actual dataGridView1_CellValueNeeded event is where the event to request more data is handled.  The included source code below provides a quick implementation of the virtual display mode – which should work for simple use cases. For a full walkthrough on a virtual mode implementation, see MSDN.

    What if the Virtual Mode is still sluggish?

    If the performance of virtual mode is still sluggish for your data (if you have several thousands of rows of data), chances are you need to look elsewhere. There are several 3rd party grid controls on the market – including Infragistics, Syncfusion and Telerik. One such grid that I have worked with extensively is Syncfusion’s Grid Control. On my project, we were handling several hundred MBs of data in the grid – with refreshes occurring in real-time or near real-time (i.e. no sluggishness).  A performance comparison is detailed in an earlier post.

    In addition to the speed, you also get a host of features that I like to call Grid on Steroids features. These include nested grids (which make it possible to efficiently display hierarchical data), multiple column sorts (which isn’t available out of the box in Windows DataGridView – but can be custom built), pivot tables and more.

    Summary

    If you are witnessing slow rendering (sluggish rendering) of your datagridview in your WinForms (or ASP.NET ) application, chances are you are using automatic binding (bound display mode). Chances are that you will experience a significant benefit from trying the virtual display mode built into the gridview. This display mode binds to a smaller, cached subset of the full data, allowing quicker UI refreshes. The sample attached here shows a grid using the bound mode and another grid using virtual mode (both with identical 10000 rows of customer data). Even with this simple sample of a few 100 KBs of data, a noticeable difference can be seen (by visual inspection) when one tries to scroll down the grid to view more rows. The refresh rate of the virtual mode grid clearly wins out.  If you find the virtual mode also insufficient for your application’s volume of data, you might need something like the syncfusion grid.

    Source Code

    Download Full Solution

    About the Author

      Anuj Varma is a Microsoft .NET architect specializing in high-performance applications. His specific expertise in the .NET framework architecture as well as 3rd party controls (such as Syncfusion) built around the framework,  makes him a sought after performance expert for .NET applications. Most recently, he has worked on an ASP.NET revamp of dell.com as well as a WinForms app used to map Ocean floors (Petrel). Both these applications were built with performance (UI performance as well as Data Access Layer performance) as a key driver. In addition to WinForms and ASP.NET apps, Anuj works hands-on in the WCF and Azure arena to bring performance to existing SOA apps. Some of Anuj’s personal websites include anujvarma.com,  AspDotnetArchitect.com and RecruitersToAvoid.com.

    The post Windows DataGridView – Improving the Data Display (Refresh) Performance appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

    ]]>
    https://www.anujvarma.com/windows-datagridview-improving-the-data-display-refresh-performance/feed/ 2