Tutorial: Best Fit Option

  • 3 minutes to read

This walkthrough is a transcript of the Best Fit Option video available on the DevExpress YouTube Channel.

Default Behavior

The grid View provides built-in column header menus where you can select the Best Fit option. This adjusts a column's width to completely display its content.

GridView_BestFitMenuItem

The same can be achieved by double-clicking a column's right edge. To adjust all columns at once, use the Best Fit (all columns) option from the column header menu.

Applying the Best Fit Option at Design Time

The same menus are available at design time, but the mentioned menu items or a header edge double-click will have no effect, since data isn't loaded. To work around this, you will need to open the grid's Designer dialog and switch to the Layout Page. This is where you can pre-load data and then apply the best fit width to columns.

GridView_BestFitInDesigner

Limiting the Number of Records to Apply Best Fit

By default, when you apply the best fit width to a column, the View checks values in all rows. This might have an unnecessary impact on performance with larger data sources. To limit the number of records the grid View scans, use the GridOptionsView.BestFitMaxRowCount property under GridView.OptionsView. In this example, set it to 3 and apply the best fit width again to see that the result differs.

GridView_BestFitMaxRowCount

Disabling the Best Fit Option

If you disable column resizing, the Best Fit option gets disabled as well – both via the context menu or by double-clicking a column header's right edge.

GridView_DisabledBestFitMenuItem

Forcing a Column to Have a Fixed Width

Restore default values for all changed options and set a column's OptionsColumn.FixedWidth option. This means that the corresponding column will keep its width when you apply the Best Fit feature to the view.

GridView_ColumnFixedWidth

Applying Best Fit in Code

Add three buttons to the UI to see how you can use this feature in code. One button will call the Grid View's GridView.BestFitColumns method that affects all columns. The second uses a column's GridColumn.BestFit method to apply the feature to an individual column. The third method gives you the most flexibility, since you can calculate the width using the GridColumn.GetBestWidth method and then adjust the value before actually applying the change to a column.


private void barButtonBestFitAll_ItemClick(object sender, ItemClickEventArgs e) {
    gridView1.BestFitColumns();
}

private void barButtonBestFit_ItemClick(object sender, ItemClickEventArgs e) {
    colProductName.BestFit();
}

private void barButtonBestFitPlus_ItemClick(object sender, ItemClickEventArgs e) {
    colProductName.Width = colProductName.GetBestWidth() + 10;
}

You can now run the application and see how all three methods work at runtime.

See Also