'Dynamically create blazor component and call its methods

I am using the MudBalzor table in my component but also want to use Syncfusion Grid as it contains some useful methods like ExportToExcel and ExportToPdf.

I want to create component of Syncfusion Grid but do not want to render it to view.

First, I try to simply create an object of that component but it didn't work, it throws a null reference when I call its methods.

SfGrid<GetEquipmentsModel> grid = new SfGrid<GetEquipmentsModel>();
grid.DataSource = data;
await grid.ExportToPdfAsync(); // inside this method it throws exception.

then I search for how to create components dynamically and found this.

var componentRef = new RenderFragment(builder => {
  builder.OpenComponent(0, typeof(SfGrid<GetEquipmentsModel>));
  builder.AddComponentReferenceCapture(1, inst => { grid = (SfGrid<GetEquipmentsModel>)inst;  });
  builder.CloseComponent();
  });

I am assuming this below line will capture the instance of a created component.

builder.AddComponentReferenceCapture(1, inst => { grid = (SfGrid<GetEquipmentsModel>)inst

await grid.ExportToPdfAsync(); // it is still trhrowing null reference exception.

but RenderFragment isn't invoked. also, i tried calling

componentRef.Invoke() //but it needs RenderTreeBuilder object which I don't know where to get from.

What I want to achieve is to create a SfGrid<GetEquipmentsModel> component in code create a column in that grid (SfGrid has a property Columns where I can add columns) Export data and that's it.

If I use that component in view and use that reference it works but that way I have to hide the component, I am thinking if I can achieve this in code without using it in view?

<SfGrid @ref="grid">
<SfGrid >

now if I use grid it will work.

I try to use a few open-source javascript libraries to export table data and they work as well but Syncfusion exporting data the same as it is in grid means using the same widths and alignments.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source