How to Add and Use a WinUI Datagrid in Your Desktop Application
Tags: webdev, tutorial, dotnet
Published: 2022-07-29 20:27:31

---
canonical_url: https://www.grapecity.com/blogs/how-to-add-and-use-winui-datagrid-in-your-desktop-application
description: Learn how to add and use a WinUI datagrid control in your desktop application. See more from ComponentOne today.
---

We live in a “big data”-driven world where people often work with massive data sets daily across multiple industries such as manufacturing, finance, banking, healthcare, retail, automotive, and many more.

Data needs to be available, manageable, and actionable throughout the organization; data grids are the key ingredient for making that happen. Data grids provide a powerful and flexible way to display/modify data in a tabular format, thanks to various features such as filtering, sorting, and grouping.

ComponentOne’s **FlexGrid** is one of the fastest data grids available in the market that renders and displays large data sets quicker than any other .NET data grids. It is a powerful grid packed with basic and advanced features like in-cell editing, sorting, filtering, merging, grouping, and more.

This article will teach us how to get started with ComponentOne’s WinUI FlexGrid. We will cover the following topics in this article:

*   [Creating a new WinUI application](#create)
*   [Adding FlexGrid to your application](#add)
*   [Creating Columns](#columns)
*   [Grouping](#grouping)
*   [Sorting](#sorting)
*   [Filtering](#filtering)
*   [Styling](#styling)

### <a id="create"></a>Creating a New WinUI Application

We will start by creating a new WinUI application.

1\. Open Visual Studio and select ‘Create a new project.’

2\. Select the 'Blank App WinUI (Packaged) project template and click ‘Next.’

![Project Template](https://files.grapecity.com/gc-website-media/qxsjxhkb/01-project-template.png?width=500&height=268.2291666666667)

3\. Set the project name and then click ‘Create.’

4\. Select the Target version & Minimum version from the opened prompt per your requirements. For example, we will select Windows 10, version 2004 & Windows 10, version 1809.

![Target Version](https://files.grapecity.com/gc-website-media/cnqm4pxb/02-target-version.png?width=500&height=191.36690647482013)

### <a id="add"></a>Adding FlexGrid to Your Application

Now we have our blank WinUI application ready. So, we will add the FlexGrid NuGet package to our application.

1\. In Visual Studio, click on the ‘Tools’ menu.

2\. Navigate to NuGet Package Manager > Manage NuGet packages for Solution.

3\. Search for the ‘**C1.WinUI.Grid**’ NuGet package and click Install.

![Flexgrid NuGet](https://files.grapecity.com/gc-website-media/pv3oyolk/03-flexgrid-nuget.png?width=500&height=245.7831325301205)

### <a id="columns"></a>Creating Columns

For the basis of a data grid, we need [**rows**](https://www.grapecity.com/componentone/docs/winui/online-winui/grid-row.html) and [**columns**](https://www.grapecity.com/componentone/docs/winui/online-winui/grid-column.html). Rows represent the objects in your data source, and Columns represent those objects' properties.

FlexGrid also comes with automatic column generation. This feature allows you to show your data with minimal to no configuration. It is excellent for simple scenarios or situations where the shape of data to be presented is determined at runtime.

Column generation can be controlled using either the familiar **Display** attribute or FlexGrid’s [**AutoGeneratingColumn**](https://www.grapecity.com/componentone/docs/winui/online-winui/C1.WinUI.Grid~C1.WinUI.Grid.FlexGrid~AutoGeneratingColumn_EV.html) event. The latter gives you complete control over the generated columns and the generation process itself.

```
    public class Player
    {
            [Display(AutoGenerateField = true, Name = "Player")]
            public string Username { get; set; }

            [Display(AutoGenerateField = true, Name = "League")]
            public string League { get; set; }

            [Display(AutoGenerateField = true, Name = "Online")]
            public bool IsOnline { get; set; }

            [Display(AutoGenerateField = true, Name = "Total Score")]
            public int TotalScore { get; set; }

            [Display(AutoGenerateField = true, Name = "Highest Score")]
            public int HighestScore { get; set; }

            [Display(AutoGenerateField = true, Name = "Last Seen")]
            public DateTime LastActive { get; set; }
    }
```

You can define manually if you need more control over what and how columns get presented. You can do quite a lot with FlexGrid’s different types of columns, such as datetime, numeric, hyperlink, image, and data. However, if you need something more, you can always define your own cell template.

```
    <UserControl
        ...
        xmlns:c1="using:C1.WinUI.Grid"
        mc:Ignorable="d">

       <c1:FlexGrid x:Name="flexGrid" ItemsSource="{Binding Players}"
                         AutoGenerateColumns="False">
           <c1:FlexGrid.Columns>
                 <c1:GridColumn Binding="Username" Header="Player">
                        <c1:GridColumn.CellTemplate>
                            <!--Sample template for demonstration-->
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal" Padding="7">
                                    <TextBlock>❂</TextBlock>
                                    <TextBlock Text="{Binding Username}"></TextBlock>
                                </StackPanel>
                            </DataTemplate>
                        </c1:GridColumn.CellTemplate>
                </c1:GridColumn>
                <c1:GridColumn Binding="League"></c1:GridColumn>
                <c1:GridNumericColumn Binding="HighestScore"></c1:GridNumericColumn>
                <c1:GridNumericColumn Binding="TotalWinnings" Format="C2"></c1:GridNumericColumn>
                <c1:GridDateTimeColumn Binding="LastActive" Header="Last Seen" Mode="Date"></c1:GridDateTimeColumn>
                <c1:GridColumn Binding="IsOnline" Header="Online"></c1:GridColumn>
           </c1:FlexGrid.Columns>
       </c1:FlexGrid>
    </UserControl>
```

The result will look something like this:

![Snap](https://files.grapecity.com/gc-website-media/to3lumfh/04-snap.png?width=500&height=244.3181818181818)

### <a id="grouping"></a>Grouping

Grouping your data is a compelling and valuable feature. FlexGrid supports grouping through the **IDataCollection** interface. It provides three overloads of the **GroupAsync** method. Refer to this[**topic**](https://www.grapecity.com/componentone/docs/services/online-datacollection/grouping.html) for more information about overload methods.

The following code shows the data grouping by 'League' through DataCollection.

```
     await flexGrid.DataCollection.GroupAsync("League");
```

You can also display the aggregate value for each group in FlexGrid by setting the [Aggregate](https://www.grapecity.com/componentone/docs/winui/online-winui/C1.WinUI.Grid~C1.WinUI.Grid.GridColumn~Aggregate.html) property on each column to one of the supported aggregate values. Some of the supported aggregate values are Sum, Average, Count, Minimum, Maximum, Custom, None, Range, Std, StdPop, Sum, Var, and VarPop.

The following code shows the sum aggregation on the TotalWinnings column.

```
    <c1:GridNumericColumn Binding="TotalWinnings" Aggregate="Sum"/>
```

And this is what our grid will look like after grouping and aggregation.

![Group](https://files.grapecity.com/gc-website-media/mdfj0c5o/05-group.gif?width=500&height=223.09899569583933)

**Note:** When you group data in a grid, the control draws expand/collapse buttons next to row groups. To collapse a group, click the ‘˅' sign, and to expand the group, click the '˃’ sign.

### <a id="sorting"></a>Sorting

Sorting is one of the essential features a grid must-have. FlexGrid allows you to control how data can be sorted in ascending or descending order for more accessible data analysis.

The easiest way of using sorting in FlexGrid is by clicking/tapping the column headers. FlexGrid’s AllowSorting property can control this feature to set whether users are allowed to sort columns by clicking the column headers.

```
    flexGrid.AllowSorting = true;
```

![Sort](https://files.grapecity.com/gc-website-media/o3opoi2q/06-sort.gif?width=500&height=223.81635581061695)

We can also enable/disable sorting on particular columns by setting GridColumn’s **AllowSorting** property.

```
    1flexGrid1.Columns[1].AllowSorting = false;
```

Another way of sorting FlexGrid is from code behind by using FlexGrid.DataCollection’s **SortAsync** method can also be used to sort multiple columns simultaneously.

```
    await flexGrid.DataCollection.SortAsync(new SortDescription("HighestScore", SortDirection.Ascending),
                    new SortDescription("TotalWinnings", SortDirection.Ascending));
```

![WinUI](https://files.grapecity.com/gc-website-media/o4ycw1ek/07-winui.png?width=500&height=225.42735042735043)

### <a id="filtering"></a>Filtering

Filtering is the most important feature of a grid as it lets you narrow down the displayed data based on a specific condition applied to a column. It is usually helpful when displaying a large dataset in the grid.

FlexGrid provides the[**GridFilterRow**](https://www.grapecity.com/componentone/docs/winui/online-winui/C1.WinUI.Grid~C1.WinUI.Grid.GridFilterRow.html) class that represents a row whose cells are text boxes used to filter the corresponding column. This class is used to show a filter row at row 0 index to filter data in grid rows. The GridFilterRow class also provides the [**AutoComplete**](https://www.grapecity.com/componentone/docs/winui/online-winui/C1.WinUI.Grid~C1.WinUI.Grid.GridFilterRow~AutoComplete.html) property, which can be used to enable auto-complete suggestions in the filter textbox based on the data in the grid.

```
    <c1:FlexGrid>
         <c1:FlexGrid.Rows>
              <c1:GridFilterRow AutoComplete="True"></c1:GridFilterRow>
         </c1:FlexGrid.Rows>
    </c1:FlexGrid>
```

And this is how it looks like on the go.

![Filter](https://files.grapecity.com/gc-website-media/m3ulx44m/08-filter.gif?width=500&height=224.53371592539457)

### <a id="styling"></a>Styling

FlexGrid allows you to customize the grid and its elements such as cell, row, column, border, and more per your application's needs and appearance.

For example, you can modify the selection and mouse hover appearance of FlexGrid by using its **MouseOverBrush**, **SelectionBackground** & **SelectionForeground** properties as follows:

```
    <c1:FlexGrid x:Name="flexGrid"
                 MouseOverBrush="LightGreen"
                 SelectionBackground="Purple"
                 SelectionForeground="White"
                ItemsSource="{Binding Players}">
                ...
    </c1:FlexGrid>
```

Similarly, you can modify other elements by using the styling API’s provided by FlexGrid. Please refer [**here**](https://www.grapecity.com/componentone/docs/winui/online-winui/styling-appearance.html) for the same.

![WinUI](https://files.grapecity.com/gc-website-media/ggdlcihc/09-winui.png?width=500&height=224.679029957204)

### Conclusion

We hope you find this article helpful to get you started with ComponentOne’s WinUI FlexGrid. We covered the most used features of a data grid in this article. But this is not the end; you could do much more with FlexGrid, such as Merging, Freezing, Paging, Live Updates, and many more. To learn more about WinUI FlexGrid & its features, you can refer [**here**](https://www.grapecity.com/componentone/docs/winui/online-winui/flexgrid.html).

You can find our sample **[here](https://files.grapecity.com/gc-website-media/05cfpddt/winuiflexgridquickstart.zip)**.

If you have any suggestions or issues while using FlexGrid, please feel free to comment, or you can also use our [**WinUI**](https://www.grapecity.com/forums/winui-edition) public forums to create a query case.