error with Grid component null

I have a simple use of the Grid Component:
    <SfGrid DataSource="@BagList)" AllowSorting="true" AllowFiltering="true" AllowSelection="true">
        <GridSelectionSettings Type="SelectionType.Single" Mode="SelectionMode.Row"></GridSelectionSettings>
        <GridEvents RowSelected="GetSelectedRecords" TValue="Data.BagView"></GridEvents>
        <GridColumns>
            <GridColumn Field=@nameof(Data.BagView.ModelName) HeaderText="Model"></GridColumn>
            <GridColumn Field=@nameof(Data.BagView.StyleName) HeaderText="Style"></GridColumn>
            <GridColumn Field=@nameof(Data.BagView.SizeName) HeaderText="Size"></GridColumn>
            <GridColumn Field=@nameof(Data.BagView.FabricName) HeaderText="Fabric"></GridColumn>
            <GridColumn Field=@nameof(Data.BagView.ColorName) HeaderText="Color"></GridColumn>
            <GridColumn Field=@nameof(Data.BagView.SeasonName) HeaderText="Season"></GridColumn>
        </GridColumns>
    </SfGrid>

@code {

    IList<Data.BagView> BagList = new List<Data.BagView>();
    SfGrid<Data.BagView> Grid;
    public List<double> SelectedRowIndexes { get; set; }

    protected override async Task OnInitializedAsync()
    {
            base.OnInitialized();
            using (var ctx = ContextFactory.CreateDbContext())
            {
                string sqlQuery = @"---sql query to fill the BagList list comes here---";
                BagList = ctx.BagViews.FromSqlRaw(sqlQuery).ToList();
            }
    }

    public async Task GetSelectedRecords(RowSelectEventArgs<Data.BagView> args)
    {
        SelectedRowIndexes = await this.Grid.GetSelectedRowIndexes();    <=========== exception is here!
        SelectedValue = SelectedRowIndexes[0];
        StateHasChanged();
    }

When I run the code the Grid gets created and everything is smooth but I click on a row to select it, it triggers GetSelectedRecords as it should but I get an error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'
<>4__this.Grid was null.

it is strange because the code is straight from Syncfusion page. 

2 Replies

MA marc March 24, 2021 02:12 PM UTC

I will leave my question here just in case someone makes the same mistake as me. But following the example on syncfusion website, I didnt notice that @ref=Grid was added next to <SfGrid ...   That explains why the Grid is mapped to the object on the page and it removes the exception Grid is null ...



JP Jeevakanth Palaniappan Syncfusion Team March 25, 2021 10:40 AM UTC

Hi Marc, 

Greetings from Syncfusion support. 

Yes. You have to set the grid instance to the @ref property in the SfGrid component. We are glad that you have resolved your issue. Please get back to us if you have any other queries. 

Regards, 
Jeevakanth SP. 


Loader.
Up arrow icon