Programmatically adding columns to data grid

Hello Radzen Team!

My app has a template selection feature, that allows multiple ways of viewing data in a grid. Some of the columns must be added on the fly because they depend on data stored in the database. First thing I noticed was that I can't add the columns on the page Load event, because the components are not yet rendered and thus are null. For now they are in a button Click event but that is not what I want, because they have to load as soon as the page opens and will stay hidden until the template is changed.

The code below adds a column for a document in my companies grid. There are lots of missing parameters.

companiesDataGrid.AddColumn(new RadzenGridColumn() { Filterable = true, Sortable = true, Title = document.name, Visible = (selectedTemplateType == (int)EnumeratorService.EN_TemplateType.Company_Documents) });

In runtime, however, the column is not filterable nor sortable, and the visible conditional does not validate, they're always visible. The title is the only thing that went correctly.

I have two questions:

  1. Is there another event that I can hook the column creation methods?
  2. How does a full RadzenGridColumn constructor looks like?

Thanks in advance!

Hi @kim,

You should not use this method to add columns to a DataGrid. By doing this you bypass the Blazor component lifecycle. The AddColumn method is only meant for internal use (we will probably make it internal to avoid such usage).

To use dynamic columns you have to declare them in in Blazor markup.

<RadzenGrid>
    <Columns>
       @foreach(var columnData in columns)
       {
          <RadzenGridColumn Property=@columnData.Property Visible=@columnData.Visible />
       }
    </Columns>
</RadzenGrid>
1 Like

How would you define the 'columns' variable in your .cs file?

You will need to create a custom class (or a tuple) to store these settings. Something like

class ColumnData
{
     public string Property { get; set; }
     public bool Visible { get; set; }
}

private IEnumerable<ColumnData> columns;

protected void OnInitialized()
{
   columns = new [] { 
     new ColumnData { Property = "FirstName", Visible = true },
     new ColumnData { Property = "LastName", Visible = false } 
   };
}
1 Like