Column width when using DataTable as itemssource

How do I set datagrid column widths when using a DataTable as the source?


The datagrid column count is zero, so I cannot access the columns. The only way of setting width is using DefaultColumnWidth, but I need columns to b


1 Reply

AP Abinesh Palanisamy Syncfusion Team November 8, 2024 12:47 PM UTC

Hi Matthew,

Based on the details provided, it appears you're using a DataTable as the ItemSource. In this case, you can set the width for the columns by using the SfDataGrid.AutoGeneratingColumn event. When SfDataGrid.AutoGenerateColumns is set to true, the SfDataGrid.AutoGeneratingColumn event is triggered for each GridColumn. The Column property in this event returns the created column, which can be customized as needed. We've included a sample and code snippets for your reference. Please review them for further details.

Code snippet :

dataGrid.AutoGeneratingColumn += GridAutoGeneratingColumns;

void GridAutoGeneratingColumns(object sender, AutoGeneratingColumnEventArgs e)

        {

            // Set column widths based on the column's MappingName.

            switch (e.Column.MappingName)

            {

                case "OrderID":

                    e.Column.Width = 40;

                    break;

                case "CustomerID":

                    e.Column.Width = 150;

                    break;

                case "Customer":

                    e.Column.Width = 200;

                    break;

                case "ShipCity":

                    e.Column.Width = 180;

                    break;

                case "ShipCountry":

                    e.Column.Width = 160;

                    break;

                default:

                    e.Column.Width = double.NaN;

                    break;

            }

      }


Regards,

Abinesh P


Attachment: SfDataGrid_86fcd16d.zip

Loader.
Up arrow icon