DEV Community

Cover image for The Definitive Guide to WinForms Datagrids
Chelsea Devereaux for MESCIUS inc.

Posted on • Updated on • Originally published at Medium

The Definitive Guide to WinForms Datagrids

A datagrid is feature-rich UI control for displaying and editing data in a tabular format. Most business data is stored in tables containing rows and columns, and the datagrid is the most straightforward way to present all data to the user. But as users have moved from traditional desktop computers to accessing data from anywhere on the web or a mobile device, the datagrid has also evolved to meet these demands.

In this article, we will share the evolution of the datagrid for developing .NET desktop Windows Forms applications, the top features you’ll find in a datagrid, how to build a WinForms datagrid, and more examples of advanced datagrid solutions.

Evolution of WinForms Datagrids

WinForms (shorter for Windows Forms) is the oldest .NET platform for building desktop software applications for Windows PCs. The .NET Framework was first released in 2002, and with it came the very first datagrid control aptly named DataGrid. It had limited features, which all required extensive code to implement.

With .NET 2.0, Microsoft introduced the DataGridView control, which is still used today. It included enhanced design-time capabilities, new data-binding features, and added some built-in features that required less code to implement, such as sorting and paging.

.NET DataGridView control

The Rise of Third Party WinForms Datagrids
In addition to the provided features and controls of .NET, Microsoft made the .NET WinForms platform extensible, allowing developers themselves to further extend the capabilities of their applications. The .NET Developer Ecosystem was born on this foundation. Companies then began developing better and more powerful controls than those included in the .NET core libraries. This ecosystem was all by design because Microsoft realized they could never provide tools for every niche in the market, and the more solutions out there, the more likely a company would invest in .NET.

Everyone wins with the availability of Third-party controls because companies can find the perfect tools to solve their needs, developers save time not having to reinvent the wheel, and Microsoft can continue to gain users of the Windows operating system.

ComponentOne FlexGrid for WinForms control

The Top Features of a WinForms Datagrid

A WinForms datagrid provides various functionalities to the applications that contain them. The primary uses include displaying, editing, and analyzing data. Let’s look at the top features for each use case and how we define them in a datagrid API.

Top Displaying Features
The WinForms datagrid display features help the user read and understand the data more quickly and more efficiently. Developers can improve how the raw data is presented to the user by making it more readable with cell formatting, merging, and column bands. Users can make the data easier to view with features like column reordering, resizing, and scrolling.

WinForms FlexGrid with collapsible row details

A more complete list of top display features include:

  • Cell formatting — Format numbers and dates such as rounding numbers, displaying percentages, and displaying dates as month names.
  • Cell merging — Adjacent cells containing the same values are merged into one larger cell either automatically by the application or manually by the user.
  • Custom cell objects — Allows the developer to put custom UI elements within a datagrid cell, such as buttons, images, or virtually anything that can be rendered in .NET. This is sometimes referred to as a Template Column.
  • Column bands — a visual grouping of related columns, such as grouping Street, City, and Postal Code under an “Address” band.
  • Column reordering & resizing — At runtime, users can change the order and size of columns to fit their needs.
  • Scrolling — Scrolling is essential to reach additional data rows and columns that don’t fit on the screen.
  • Collapsible row details — Displays less important information about a record within a collapsible panel on each row.
  • Frozen columns and rows — Affixes any number of rows and columns to keep them from scrolling out of view.
  • Right-to-Left — Flips the columns and text to read from right to left, which is critical for some cultures.
  • Themes and styles — Provide more than one look and feel to deliver modern-looking or company-branded UIs. A rich UI control provides extensive style customization.

Top Editing Features
The WinForms datagrid editing features enable users to insert, update, and even delete data at the underlying source. While extra code is typically required to complete the connection and pass updates to the data source, the datagrid control is responsible for accepting the input from the user in the most efficient and intuitive ways possible.

WinForms FlexGrid with input validation errors

For example, when you need to make your SQL Server data editable by a user (who may not be comfortable using SQL Server tools), you can build a WinForms over data application containing a datagrid bound to the data tables. Users can navigate the datagrid cell by cell and insert or edit the values. Additional editing features include adding new rows, input validation, clipboard support, importing data from external files, and even specialized cell editors such as calendars for dates, checkboxes for Boolean values, etc. A more complete list of top editing features includes:

  • Cell navigation & editing by keyboard — Allows the user to navigate and edit cells through the keyboard. We often follow Microsoft Excel behavior using a combination of the tab, arrow, control, and enter keys to perform all editing operations.
  • Read-only cells and columns — Gives the developer the ability to make any column or cell non-editable.
  • Input masking & validation — Prevents the user from entering invalid information, such as poorly formatted emails, IDs, phone numbers, location, and date ranges.
  • Select cells — Allows the user to select or highlight any number of rows or individual cells. The cell selection is often used for additional drill-down or export, so the developer may restrict the selection based on the application requirements.
  • Add new rows — Allows the user to add new records to the data source through the datagrid itself. While many UI designers choose a separate input form for this operation, it’s helpful to have this feature in the datagrid, too, for quicker solutions.
  • Delete rows — Allows the user to delete records from the data source through the datagrid itself. This can be supported with the delete key or a button embedded in a cell.
  • Custom cell editors — The developer can specify a specialized editor for certain columns and data types. For example, editing colors is best implemented with a color picker rather than a textbox.
  • Clipboard support — Users can use their keyboard’s cut, copy and paste commands to edit the datagrid.
  • Importing data — Import tabular data from common sources like Microsoft Excel, CSV, JSON, and XML.

Top Analyzing Features
While displaying and editing data are the most common use cases, the true potential of a WinForms datagrid lies in its analytical features. Datagrids make great analysis tools — especially for creating “live” reports and are often included in dashboards.

WinForms FlexGrid control with tree-grid subtotals

Advanced WinForms datagrids typically include analytical features such as sorting, grouping, and filtering. These actions allow the user to drill-down, slice, and aggregate the entire data set to discover trends and insights on the data set. For example, sorting and grouping allow the user to organize the data meaningfully to find the highest or lowest records. Filtering is an essential feature that lets the user search and find specific records. A more complete list of top analyzing features includes:

  • Sorting by column — Allows the user to sort the entire datagrid by a single column’s values in ascending or descending order. This is typically performed by clicking the column header and displaying an up or down arrow.
  • Sorting by multiple columns — Allows the user to perform a sort across multiple columns at the same time. This is typically performed by clicking the column header while simultaneously pressing a key.
  • Grouping by column — Allows the developer to group the data within the datagrid by a single column, which organizes the data similarly to sorting but with added header rows to separate each group.
  • Drag-and-drop Grouping — Allows the user to perform grouping at runtime by dragging any number of column headers into a grouping panel or by grouping through a menu.
  • Excel-like Filtering — Provides filters within each column header to enable conditional and value-based filters for the user.
  • Filter row — Provides a filter input box for each column in a fixed row at the top or bottom of the datagrid.
  • Full-text filtering (search box) — Provides filtering functionality to the datagrid from an external text box. This is commonly referred to as “searching” as it feels like a Google search box for your datagrid.
  • Subtotals and aggregates — When a datagrid is grouped it may optionally display aggregated subtotals for each group. The aggregated values are typically displayed in the group header row. Totals may also be calculated for the entire data set and displayed at the bottom footer of the datagrid.
  • Conditional formatting — Applies special formatting to cells based on their value. A common example is shading cells with different colors based on different thresholds.
  • Custom calculations — With custom columns, you can provide additional calculations that may not be present in the raw data. For example, if your data set includes column fields for “Price” and “Discount”, the datagrid could display a custom column with a calculation of Price*Discount.

DataGridView Features vs Third Party Datagrids

The features above only scratch the surface of what a WinForms datagrid can do. Advanced and niche features can include exporting to Microsoft Excel, multi-level hierarchical views, transposing the rows and columns, multi-line rows, and so much more. The .NET DataGridView includes many top features built-in, but to implement other features, you have to write code to extend the control. Alternatively, you can save a lot of time by licensing a Third-party datagrid library. Let’s look at how the standard DataGridView stacks up against a popular Third-party WinForms datagrid, such as the ComponentOne FlexGrid.

Essential WinForms Control Features
We should first look at essential features that impact the usage of the datagrid control in Microsoft Visual Studio, the official .NET development environment. With .NET WinForms applications, there are two modes for each form, commonly referred to as design-time and code-behind.

  • Design-time — This is when you’re working in the drag-and-drop, WYSIWYG designer view of your form in Visual Studio. You can configure much of your application UI through the designer without writing much code. Of course, code is still being written, but it’s automatically managed by Visual Studio.
  • Code-behind — This is the C# or VB.NET code file associated with each form. Here, you write your custom business logic, such as data-binding and event handling.

Data-binding is a common feature in software UI development, and it refers to connecting the user interface to a data source. The binding can be one-way (read-only), two-way (editable), or the control can support unbound scenarios where the rows and columns are generated empty. Here is how the DataGridView stacks up against the ComponentOne FlexGrid.

DataGridView Features

Every .NET control provides basic event handling and design-time support which includes draggable handles to resize and position the control on the form, as well as a property grid. Third party datagrids like FlexGrid typically provide a richer design-time experience which includes context sensitive selection (i.e., you can select an individual column to modify its properties) and extra editors and dialogs that help manage every aspect and key feature.

WinForms Datagrid Display Feature Comparison
The standard .NET DataGridView provides basic features and extensibility, but it does not have many built-in features. A built-in feature typically means that it’s enabled with very little code — often by setting just one property. Here are how the top (built-in) display features stack up against a Third-party datagrid like FlexGrid.

Display Features

WinForms Datagrid Editing Feature Comparison
The DataGridView is primarily designed for editing as you can get a quick, barebones table editor by simply databinding. A feature that’s not supported is not impossible, but it means more code must be written. Here’s a comparison of the editing features.

Editing Features

WinForms Datagrid Analysis Features
The DataGridView is designed primarily for displaying and editing. If you’re looking for more advanced features that fall into the analysis category, you’ll find more of these features built into Third-party datagrids, as you can see below.

Analysis Features

The trade-offs to getting more built-in features with a Third-party datagrid are extra steps to acquire the libraries and extra costs associated with licensing the control. Next, let’s look at how to use a WinForms datagrid control.

How to Build a WinForms Datagrid

Follow these steps to get started using the WinForms DataGridView or a Third-party datagrid such as the ComponentOne FlexGrid control.

Step 1: Setup the Application
To begin building a .NET WinForms application, you must first install Visual Studio with .NET tools.

WinForms_Datagrid_Create_New_Project

Create a new project using the “Windows Forms App” project template for C# and select .NET 8 on the subsequent window. Notes:

  • You can also choose VB.NET but my code examples below are for C# only.
  • If you’re reading this in the future you can choose a newer version of .NET.

Step 2: Add the Datagrid Control to the Application
Open the Form1.cs file in design view and expand the Toolbox window. If you can’t find the Toolbox, then select it from the View menu.

Working with DataGridView

WinForms_Datagrid_DataGridView

  • Locate the DataGridView control in the Toolbox under the Data control group.
  • Drag and drop the DataGridView to the form surface.

Working with FlexGrid

WinForms_Datagrid_NuGet_Package_Manager

  • Open the NuGet Package Manager from the Tools menu and select Manage NuGet Packages for Solution…
  • On the Browse tab, search for C1.Win.FlexGrid.
  • Select the project on the right and install the latest version from nuget.org.
  • Locate the C1FlexGrid control in the Toolbox.
  • Drag and drop the C1FlexGrid control to the form surface.

With the control selected, open the smart tag (>) and set Dock in Parent Container. This will sets its Dock property to expand the control and fill the entire form.

WinForms_Datagrid_FlexGrid

Most Third-party libraries will work with a free 30-day trial. You may be prompted to visit the company’s website to start the trial, or it may be configured to work with just the NuGet Package.

Step 3: Configure the Data Source
To see the datagrid in action, we need to set up a sample data source. You can use the sample code below or replace this section with your own code.

Right-click the Form1.cs file in the Solution Explorer window and select View Code. Then, replace the code with the following.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var people = new List<Person>();
        people.Add(new Person() { Name = "Jeremy", Age = 25 });
        people.Add(new Person() { Name = "Michelle", Age = 29 });
        people.Add(new Person() { Name = "Caitlyn", Age = 23 });

        // bind the datagrid
        c1FlexGrid1.DataSource = people;
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

This generates a simple list of objects and assigns it to the datagrid’s DataSource property. If you’re using DataGridView, replace the c1FlexGrid1 with the name of the control.

Step 4: Build, Run and Customize!
You can now build and run the application to see the datagrid in action. Then, you can explore the API through Visual Studio Intellisense and the Properties window to configure features.

WinForms_Datagrid_Form1

Many datagrid features can be enabled through properties on the control itself. We can’t possibly cover the implementation of every feature in this article, but we can share a tip. Due to the database nature of the datagrid, you’ll also find many features at the column level. This means the API is on the column and can be set through the Columns (DataGridView) or Cols (FlexGrid) properties.

How to Optimize the WinForms Datagrid Performance
Performance is a key feature that is a more complex topic. It has many variables and considerations. The common performance techniques for a WinForms Datagrid include:

  • Suspending rendering during configuration — Painting the datagrid is an expensive operation, so it can save time to suspend painting in the middle of configuration.
  • UI virtualization — this technique recycles UI elements used to draw the cells as the datagrid is scrolled. So if you have 10,000 rows there are not actually 10,000 rows being rendered — typically the datagrid library will draw just enough that’s visible plus some offset to make scrolling appear seamless.
  • Data virtualization — beyond the datagrid you can further optimize performance for large data sets by pulling it from the source in pages or segments. A traditional view of data virtualization is with paging, but modern datagrids like the FlexGrid can achieve the same feature with traditional vertical scrolling.
  • Deferred scrolling — Since painting the datagrid is an expensive operation, it means that scrolling puts a lot of stress on the performance limits. Deferred scrolling is a simple technique that tells the datagrid to suspend rendering of the cells until after the user stops moving the scroll thumb.

UI Virtualization is typically baked into the control, and there’s nothing you need to enable. Deferred scrolling is typically a built-in feature that needs to be enabled. Data virtualization is, by nature, the least built-in feature and requires the most configuration to implement. You should check out the documentation to learn more about rendering options.

Specialized WinForms Datagrid

The sky is typically the limit regarding software development, so it’s no surprise that there’s still a lot more you can do with a WinForms datagrid. Developers and teams alike can keep adding more and more features to a single datagrid library, but at a certain point, it makes more sense to branch some features off into a specialized datagrid control. Some popular examples of specialized datagrids include:

Gantt Views
A datagrid specialized in managing projects and tasks with drag-and-drop editing and chart-like graphics.

WinForms_GanttView_Grouping

Pivot Tables
A datagrid that displays a cross-tab view of one or more dimensions with built-in aggregation and extensive runtime configuration.

WinForms_FlexPivot_WindowsTheme

Spreadsheets
A datagrid that specializes in unbound editing and manipulation similar to Microsoft Excel with built-in calculations and formulas.

WPF_FlexSheet_Sparkline

Conclusion

The WinForms DataGridView is good control for simply viewing and editing tabular data in your .NET applications. For more advanced features, such as built-in analysis and themes, you will want to explore third party WinForms datagrids. You can use the feature list from this article as a checklist when you compare different third-party datagrids. The screenshots used throughout are taken from the ComponentOne FlexGrid datagrid control, which you can learn more about from here.

Top comments (0)