A WPF datagrid is a user interface control for displaying, editing, and analyzing large data sets within a Windows desktop application. You can think of a datagrid like a spreadsheet table with features like column sorting, column resizing, and built-in cell editing bound to your data source. WPF (Windows Presentation Foundation) is a .NET framework for developing modern desktop applications with C# or VB.NET code.
In this article, we discuss the evolution of the .NET datagrid, the top features of a WPF datagrid, and how to use a datagrid in your WPF application code.
The Evolution of WPF DataGrids
Technically, the first .NET datagrid control was introduced with .NET version 1.0 and Windows Forms, which was the successor to Visual Basic 6.0 and the beginning of the still-flourishing .NET framework ecosystem. Windows Forms was the preferred option for developing a desktop Windows application until .NET 3.0, when Microsoft added WPF to the .NET stack of frameworks. WPF added many improvements over Windows Forms, but most significantly, it added better data binding, styling, and performance enhancements. One key difference of WPF was how developers created user interfaces. WPF was the first .NET platform to use XAML with a datagrid among its core UI components.
The same WPF DataGrid control that was released with .NET 3.0 is still used today with .NET 8.0. Now, let’s look at the features.
The Standard .NET WPF Datagrid Features
The WPF DataGrid offered a slightly different feature set than the Windows Forms version (the DataGridView). It added grouping and row details, providing a cleaner way to organize data. It supports sorting by multiple columns, and its cell template design made it much easier to customize cell contents, such as conditional formatting and custom cell editors.
You’ll find a complete list of features later in this article. To see how these features compare to the Windows Forms DataGridView, check out our previous blog, The Definitive Guide to .NET C# Datagrids.
Third-Party WPF Datagrids
Despite being considered an upgrade from the Windows Forms datagrid, the WPF DataGrid has always felt like it was missing some features. The default style requires you to customize its appearance from the get-go. Additionally, developers ran into limitations with the standard WPF DataGrid and didn’t want to write colossal amounts of code to implement advanced features.
That is where third-party WPF datagrids come into play. The .NET ecosystem has always supported custom components that you can build yourself or purchase from other software development teams.
Third-party datagrids come with more built-in features (enabled with very little code — often by setting just one property) than the default Microsoft datagrid, including:
- Multi-level grouping for hierarchical display
- Multi-column sorting to make fundamental analysis easier
- Auto-sized columns and rows–for responsive applications
- Rich design-time support for configuring appearance and behavior without writing any code
- Advanced cell customization for editing and visualizing unique data
- Unbound columns for more accessible, dynamic data display
- On-demand loading of rows with data virtualization and “skeleton” loading
- Merge/split cells and rows, similar to Microsoft Word and Excel
- Flexible styling options to apply custom branding to the user interface
- Freezing and pinning columns, similar to Microsoft Excel
- Custom printing and export to popular formats like Excel, CSV, HTML, and PDF
For example, the ComponentOne FlexGrid is a cross-platform .NET datagrid with a WPF version that supports .NET Framework 4.6.2 up through .NET 8 as of this writing. It supports the same production-ready features as the WPF DataGrid control but also accelerates C# development with all the built-in features listed above.
Those are just some of the feature highlights. Next, we’ll look at the full feature set for a typical C# or VB.NET datagrid and how the features compare between different grid controls.
The Top Features of a WPF Datagrid
The top datagrid features can be divided into three categories for displaying, editing and analyzing data. Let’s compare these key features for the standard WPF DataGrid and the third-party FlexGrid control.
WPF Datagrid Display Features
Display features help the user read and understand the data more quickly and efficiently. You can improve the readability of the raw data with cell formatting, merging, and column bands. See how the top (built-in) display features stack up against a third-party datagrid, like FlexGrid, below:
WPF Datagrid Editing Features
Editing is a critical feature as datagrids, like spreadsheets, are often used for batch editing. The standard WPF datagrid provides basic features and extensibility but does not have as many built-in features as most third-party datagrids.
WPF Datagrid Analysis Features
In addition to displaying and editing data, datagrids can be great tools for basic data analysis. Analysis features are where you’ll find the greatest divide between the standard WPF DataGrid and third-party controls.
Customizing vs. Purchasing a DataGrid
One of the benefits of WPF is that it’s the most easily extensible .NET platform due to its XAML-based architecture. With XAML, we can customize templates of components to add extra features. While that’s still more development work than setting a built-in feature, it’s still a lot easier than extending a control in Windows Forms or for the web.
For example, many WPF DataGrid features require custom converters and styles or rely on configuring the CollectionViewSource. While these may not be “built-in” the same way as WinForms, they are fairly easy to implement, given the nature of the platform. We’ve denoted the “fairly-easy-to-implement” features with a green check in the table above.
The trade-offs to purchasing a third-party datagrid are the extra steps to acquire the libraries and the extra costs associated with licensing the control. However, for the purchase price, you save development time by not having to implement as many custom features. Next, let’s look at how to build and use a WPF datagrid control.
The ComponentOne products are provided by MESCIUS, but you can also download their WPF datagrid on nuget.org.
How to Add a WPF Datagrid to Your .NET Application
This section is a tutorial on getting started on building a WPF application and working with the standard DataGrid control.
Step 1: Set Up the Application
To begin building a .NET WPF application, you must first install Visual Studio with .NET tools.
Create a new project using the “WPF Application” project template for C# and select .NET 8 on the subsequent window. Notes:
- You can also choose VB.NET, but our 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.
- Locate the DataGrid control in the Toolbox under the common control group.
- Drag and drop the DataGrid to the designer window.
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.
Open the MainWindow.xaml.cs file in the Solution Explorer window and replace the MainWindow class with the following code and additional Person class.
public partial class MainWindow : Window
{
public MainWindow()
{
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
dataGrid.ItemsSource = people;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
This generates a simple list of objects and assigns it to the datagrid’s ItemsSource property.
In your actual application, the data could be coming from a web service, SQL Server, JSON file or another source. The datagrid is data agnostic, so the source of the data does not matter, but you will need to convert the data to a collection type that the datagrid control recognizes, like a List or ObservableCollection.
Step 4: Build and Run
You can now build and run the application to see the datagrid in action.
In this scenario, we simply data-bind and build! Every datagrid control automatically generates columns for each field and comes with basic editing and sorting features out of the box. In simple cases, this is all you need, but notice that every column will display in the exact order as they are discovered in the data source.
Step 5: Customize the Columns
The WPF datagrids will automatically generate all the columns based on your data source. Rarely will the columns be in your or your user’s preferred order, so, in most cases, you will want to reorder or hide some columns.
In WPF, we use XAML to define the UI, which is the best place to define the columns. Once the columns are defined in XAML, you can easily rearrange, remove, and format each one.
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
</DataGrid.Columns>
</DataGrid>
Note that you must set the AutoGenerateColumns property to False unless you want the combined effect of autogenerated columns and manually defined columns. However, there is also a good use for that scenario, such as adding custom columns to your data source.
Next, you can explore the column API through Visual Studio IntelliSense and the Properties window to configure additional features.
Advanced Customization with FlexGrid
This section provides a tutorial on using the third-party FlexGrid control from MESCIUS for comparison. It requires that you first complete the tutorial above to set up the application and data source.
If you need more than the built-in editing, sorting, and moderately-easy column customization, then you are likely looking at needing advanced datagrid customization. These advanced features can include:
- Grouping by columns
- Editing with custom cell editors
- Displaying custom objects in cells
- Creating hierarchical grids with collapsible rows and drill-down details
- Filtering by drop-down menus or a filter row
- Freezing columns and rows in place during scroll
Some of these features are possible with the standard datagrid, but others require writing a lot more code. If you use a third-party datagrid, you can enable most of these features rather quickly with just a few lines of code. Let’s replace the DataGrid control with FlexGrid, and then we’ll continue to customize it with advanced grouping and filtering.
Step 1: Replace the WPF DataGrid with FlexGrid
- Open the NuGet Package Manager from the Tools menu and select Manage NuGet Packages for Solution…
- On the Browse tab, search for C1.WPF.Grid.
- 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.
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. FlexGrid will automatically install and start a 30-day free trial from its NuGet build script.
The same data source code will also work with the FlexGrid control if you use the same name, but the XAML is quite different to customize the columns:
<c1:FlexGrid x:Name="dataGrid" AutoGenerateColumns="False">
<c1:FlexGrid.Columns>
<c1:GridColumn Header="Age" Binding="Age" />
<c1:GridColumn Header="Name" Binding="Name" />
</c1:FlexGrid.Columns>
</c1:FlexGrid>
Step 2: Implement Search Box Filtering with No Code
There are many different ways to implement filtering in a .NET datagrid. You could display a filter panel next to the grid. You could add a traditional filter row fixed at the top of the datagrid. You could create Microsoft Excel-like filtering with menus.
ComponentOne FlexGrid for WPF supports all of these styles of filtering. Perhaps the quickest and easiest to implement is the SearchBox style filtering, also known as “full-text filtering.”
All you have to do is add a TextBox to your Window and data-bind it to the FlexGrid FullTextFilterBehavior.
1.Add a TextBox above the FlexGrid. The XAML may look like this:
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Filter: " />
<TextBox x:Name="filterTextBox" Width="100"/>
</StackPanel>
2.Select the FlexGrid on the design window and open the Suggested Actions menu (lightbulb icon).
3.On the Behavior tab, select the FullTextFilterBehavior and click Add Behavior.
4.Expand the Behavior within the tab and create a new databinding to the TextBox in the FilterEntry row. You’ll have to navigate into the Grid layout control to find and select the TextBox.
5.Build and run the application. Now, you’ll observe that when you type in the TextBox, the FlexGrid automatically filters.
Check out the WPF datagrid documentation for more tips and tutorials using FlexGrid.
Conclusion
The .NET DataGrid control for WPF is still supported and used today with .NET 8.0 (and soon .NET 9.0) Windows desktop applications. The standard DataGrid control is a great starting point for basic functionality. Open-source and third-party component vendors like ComponentOne, Infragistics, and Telerik have filled in the gaps left open by the core .NET framework. The costs of developing the features yourself are typically higher than buying off-the-shelf. Third-party libraries pay for themselves with the saved time and resources.
Top comments (0)