How to set column widths to a specified width in the grid

I can see the various modes to calculate column widths in the grid but I want to programmatically set  the widths of each column to my own fixed values. How do I do that?


1 Reply

DM Dhanasekar Mohanraj Syncfusion Team August 3, 2022 02:26 PM UTC

Hi David Adler,

You can achieve your requirement to set the width for the columns through the below ways,

Case 1: Manually defining columns

When you are defining columns manually, you can set the column width using the Width property shown below,

sfDataGrid1.AutoGenerateColumns = false;

sfDataGrid1.DataSource = viewModel.OrdersListDetails;

this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "OrderID", HeaderText = "Order ID", Width=150 });

this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "CustomerID", HeaderText = "Customer ID" , Width=200 });


Case 2: Auto-generating columns

When you are using auto-generating columns you can set the column width using SfDataGrid.AutoGeneratingColumn event like shown below,

sfDataGrid1.AutoGenerateColumns = true;

sfDataGrid1.AutoGeneratingColumn += SfDataGrid1_AutoGeneratingColumn;

private void SfDataGrid1_AutoGeneratingColumn(object sender, Syncfusion.WinForms.DataGrid.Events.AutoGeneratingColumnArgs e)

 {

     if (e.Column.MappingName == "OrderID")

         e.Column.Width = 150;

     if (e.Column.MappingName == "CustomerID")

         e.Column.Width = 200;

 }


For more information related to columns generation and autogenerating column events, please refer to the below user guide documentation link,

UG Link:

https://help.syncfusion.com/windowsforms/datagrid/columns#manually-defining-columns

https://help.syncfusion.com/windowsforms/datagrid/columns#customize-auto-generated-columns

Please let us know if you have any concerns about this.


Regards,
Dhanasekar M.



Loader.
Up arrow icon