Skip to main content Skip to footer

How to Customize C# Datagrid Features in Your Desktop App

ComponentOne FlexGrid is a fast and flexible .NET datagrid that delivers high-performance features and familiar, Microsoft Excel-like experiences. FlexGrid is primarily used for traditional editing, visualizing, and analyzing tabular data. Still, its super flexible API helps developers go beyond with full control and customization down to the cellular level!

In this blog post, we’ll look at how to customize the FlexGrid with quick C# code snippets. FlexGrid is also supported across the entire Microsoft .NET stack with (nearly) the same API, so this blog compares features among desktop, web, and mobile .NET platforms.

In this post, we cover:

Ready to Get Started? Download ComponentOne Today!

Performance Optimization Techniques

FlexGrid is developed using UI virtualization, which optimizes the creation, movement, and recycling of UI elements contained within the cells. There’s nothing you need to do to get it, but there are some additional optimization techniques you can use to handle large data sets better.

Data Virtualization

Data virtualization (or Virtual Mode) is the process of loading data from remote sources in an incremental manner instead of loading it all at once. With FlexGrid, the data is loaded incrementally as the user scrolls down the grid. This process is beneficial while dealing with large data sets as it reduces initial load time.

Data virtualization is supported in our .NET datagrids through the C1DataCollection library. The process is to implement your own CollectionView by extending our C1VirtualDataCollection specific to your data object. Then, set this to the FlexGrid’s data source.

using C1.DataCollection;

MyVirtualModeCollectionView collectionView = new MyVirtualModeCollectionView();
c1FlexGrid1.DataSource = new C1DataCollectionBindingList(collectionView);

public class MyVirtualModeCollectionView : C1VirtualDataCollection<Customer>
{
    public int TotalCount { get; set; } = 1_000;

    protected override async Task<Tuple<int, IReadOnlyList<Customer>>> GetPageAsync(int pageIndex, int startingIndex, int count, IReadOnlyList<SortDescription> sortDescriptions = null, FilterExpression filterExpression = null, CancellationToken cancellationToken = default(CancellationToken))
    {
        await Task.Delay(500, cancellationToken);//Simulates network traffic.
        return new Tuple<int, IReadOnlyList<Customer>>(TotalCount, Enumerable.Range(startingIndex, count).Select(i => new Customer(i)).ToList());
    }
}

Paging C# Sample for FlexGrid

Virtualization is the best technique for optimizing performance because it limits the number of records drawn from the data source. However, some desired solutions may not require as much optimization, or the data source may not support them. Another technique is paging. The full data is loaded with standard .NET paging, but only one page is displayed at a time. This offers some UI performance optimization, as well as offers perceived performance.

Winforms Flexgrid Paging

The following C# code snippet demonstrates how paging is implemented and uses the BeginUpdate/EndUpdate methods for added performance optimization. Download the full sample for the complete implementation.

public void UpdateGrid()
{
    using (OleDbConnection conn = new OleDbConnection(GetConnectionString()))
    {
        string sql = $"SELECT * FROM [{TABLE_NAME}]";
        OleDbDataAdapter pagingAdapter = new OleDbDataAdapter(sql, conn);
        DataSet pagingDS = new DataSet();

        //Get limited data from database
        pagingAdapter.Fill(pagingDS, DB_INDEX, ROWS_PER_PAGE, TABLE_NAME);

        c1FlexGrid1.BeginUpdate();

        c1FlexGrid1.DataSource = pagingDS;
        c1FlexGrid1.DataMember = TABLE_NAME;

        c1FlexGrid1.EndUpdate();
    }
}

For more tips and tricks on performance, check out How to Build and Optimize FlexGrid, the Fastest WinForms Datagrid.

Customize the Datagrid Styles

Styling a .NET datagrid can refer to application-wide themes or conditional styling (or formatting) for individual cells. While the application-wide theming techniques vary greatly between .NET platforms, the cell styling in FlexGrid is more or less the same.

Create a custom style

You can create a custom CellStyle and give it attributes like background color and text color. FlexGrid already includes a built-in cell styles collection to which you can add yours.

//Creating a custom style 
CellStyle cs1 = c1FlexGrid1.Styles.Add("NewStyle");
cs1.BackColor = Color.Aqua;
cs1.ForeColor = Color.Blue;

You can even customize your cell styles at design-time by clicking the “Styles” link on the FlexGrid properties.

Winforms Flexgrid Cell Style Editor

Apply the cell style conditionally

The next step is to set the cell style to certain cells that meet your criteria. FlexGrid lets you easily access cell values using simple [row,col] indexing, so you can cycle through all rows and cells and set each cell style. A smarter approach is to take advantage of the OwnerDrawCell event. This event fires when each cell is rendered, allowing you to override or add custom logic. Set the DrawMode property to OwnerDraw and then set up some simple if/else logic in the event.

The following code snippet applies our “NewStyle” to cells in column #6 with values greater than 500.

c1FlexGrid1.DrawMode = DrawModeEnum.OwnerDraw;
c1FlexGrid1.OwnerDrawCell += FlexGrid_OwnerDrawCell;

private void FlexGrid_OwnerDrawCell(object sender, OwnerDrawCellEventArgs e)
{
    if(e.Col == 6)
    {
        var value = c1FlexGrid1[e.Row, e.Col];
        double d;
        if(double.TryParse(value.ToString(), out d))
        {
            if(d >= 500)
            {
                c1FlexGrid1.SetCellStyle(e.Row, e.Col, flexGrid.Styles["NewStyle"]);
            }
        }
    }
}

WInforms Flexgrid Cell Styles

For more information on cell styling, check out How to Style Cells in Your .NET Datagrid Application.

Export the Datagrid at Runtime

FlexGrid for WinForms can be exported to Excel, CSV, HTML, plain text, and even images at runtime by the user. These formats are built into the library, and with minimal additional code, you can even export them to PDF.

Exporting to Excel

To export FlexGrid to Excel, call the SaveExcel method and pass in the file path and file flag options.

c1FlexGrid1.SaveExcel("../../ExportedGrid.xlsx",  
    FileFlags.AsDisplayed | FileFlags.IncludeFixedCells);

The file flag options allow you to include fixed cells, export visible rows only, freeze rows, and more. For more, check out our documentation.

Exporting to PDF

The easiest way of saving FlexGrid as a PDF is to use the built-in “Microsoft Print to PDF” feature of Windows PrintDocument. By setting this printer type, you can simply invoke the FlexGrid’s Print method, and the user will be prompted to save the file somewhere.

var printDocument = _flexGrid.PrintParameters.PrintDocument;
printDocument.DocumentName = "Export to PDF";
printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";
// Print document into Microsoft PDF printer
 printDocument.Print();    

Note that the same approach can be used for traditional printing. Also, note that this approach is for quick printing/exporting, but it does not let you set advanced options such as borders, printing by specific page or column breaks, etc. We show how you can implement these features using our C1PrintDocument - see Advanced Export to PDF.

Ready to Get Started? Download ComponentOne Today!

comments powered by Disqus