Limit DataTable columns added when AutoGenerateColumns = true

1 Answer 33 Views
DataGrid
Paul
Top achievements
Rank 1
Paul asked on 05 Jun 2024, 12:02 AM

Is there a way to limit DataTable columns added when AutoGenerateColumns = true ?

Example: DataTable has columns A, B, C, D, E and I want everything but A and D to be in the RadDataGrid

Not having success by finding the column by name and setting IsVisible = false.

Another related question. Is there a way in C# to set column properties for auto generated columns like width or displaying checkbox for bool columns?

Thanks !

1 Answer, 1 is accepted

Sort by
0
Yana
Telerik team
answered on 05 Jun 2024, 08:33 AM

Hi Paul,

You can use the GenerateColumn command (DataGrid: Commands Overview) in order to access the columns and set some properties to them. Here is a quick example based on the DataGrid Binding to DataTable example:

1. Create a custom MyGenerateColumnCommand which inherits from DataGridCommand - inside its Execute method you can get the property the column is created for, and do not call the default logic for creating columns for some properties. In addition, you can take the column after it's generated and set some properties:

public class MyGenerateColumnCommand : DataGridCommand
{
    public MyGenerateColumnCommand()
    {
        Id = DataGridCommandId.GenerateColumn;
    }
    public override bool CanExecute(object parameter)
    {
        return true;
    }
    public override void Execute(object parameter)
    {
        var context = parameter as GenerateColumnContext;

        if (context != null && context.PropertyName != "Population")
        {
            this.Owner.CommandService.ExecuteDefaultCommand(DataGridCommandId.GenerateColumn, parameter);
            var textColumn = context.Result as DataGridTextColumn;
            if(context.PropertyName == "City" && textColumn != null)
            {
                textColumn.SizeMode = DataGridColumnSizeMode.Fixed;
                textColumn.Width = 200;
            }
        }
    }
}

 

2. Apply the custom command to the DataGrid instance:

<telerik:RadDataGrid x:Name="grid" 
                    ItemsSource="{Binding Data}">
    <telerik:RadDataGrid.Commands>
        <local:MyGenerateColumnCommand />
    </telerik:RadDataGrid.Commands>
</telerik:RadDataGrid>

In addition, if you need to display checkbox for bool columns, you'd need to customize the corresponding columns' cell templates as described here: Data Grid Columns: Cell Templates.  You can set the custom CellColumnTemplate inside the GenerateColumn command as well.

I hope I was of help. Let me know if I can help with anything else.

Regards,
Yana
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
DataGrid
Asked by
Paul
Top achievements
Rank 1
Answers by
Yana
Telerik team
Share this question
or