Removing columns

Hello,
I try to use data grid in Blazor server application on the latest stable version (18.1.0.42). 
I have created a generic component which has a generic datasource bind to grid.
I see all records in the datasource within the grid. Till now everything is ok.
I try to remove some columns in the grid. 

    SfGrid<TData> grd;
    [Parameter] public string[] DeletedColumns { get; set; }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (grd.Columns != null)
        {
            foreach (var item in DeletedColumns)
            {
                int i = FindIndex(item);
                if (i >= 0) ((List<GridColumn>)grd.Columns).RemoveAt(i);
            }           
            grd.RefreshColumns();
            grd.RefreshHeader();
            grd.Refresh();
        }
        return Task.FromResult(0);
    }

    int FindIndex(string columnName)
    {
        int i = 0;
        int index = -1;
        List<GridColumn> columns = (List<GridColumn>)grd.Columns;
        foreach (GridColumn item in columns)
        {
            if (item.Field == columnName)
            {
                index = i;
                break;
            }
            i++;
        }
        return index;
    }


as expected columns are removed from the grid. But column header are still there. So, whole columns shift to left side and everything is getting confusing.


These errors are shown in the console.

Uncaught (in promise) Error: System.InvalidOperationException: Sequence contains no elements
   at System.Linq.ThrowHelper.ThrowNoElementsException()
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Syncfusion.Blazor.Grids.Internal.GridUtils.grabColumnByUidOrField(String Uid, IGrid Parent, String Field)
   at Syncfusion.Blazor.Grids.Internal.GridJSInteropAdaptor`1.setColumnVisibility(Object args)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.InvokeSynchronously(JSRuntime jsRuntime, DotNetInvocationInfo& callInfo, IDotNetObjectReference objectReference, String argsJson)
   at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.BeginInvokeDotNet(JSRuntime jsRuntime, DotNetInvocationInfo invocationInfo, String argsJson)
    at Object.endInvokeDotNetFromJS (http://localhost:5000/_framework/blazor.server.js:8:31660)
    at e.<anonymous> (http://localhost:5000/_framework/blazor.server.js:8:103446)
    at http://localhost:5000/_framework/blazor.server.js:1:19202
    at Array.forEach (<anonymous>)
    at e.invokeClientMethod (http://localhost:5000/_framework/blazor.server.js:1:19173)
    at e.processIncomingData (http://localhost:5000/_framework/blazor.server.js:1:17165)
    at e.connection.onreceive (http://localhost:5000/_framework/blazor.server.js:1:10276)
    at WebSocket.i.onmessage (http://localhost:5000/_framework/blazor.server.js:1:38091)

syncfusion-blazor.min.js:1 Cannot read property 'style' of undefined
TypeError: Cannot read property 'style' of undefined
    at http://localhost:5000/_content/Syncfusion.Blazor/scripts/syncfusion-blazor.min.js:1:73659
    at Array.forEach (<anonymous>)
    at Object.$e [as setStyleAttribute] (http://localhost:5000/_content/Syncfusion.Blazor/scripts/syncfusion-blazor.min.js:1:73636)
    at e.setDisplayNone (http://localhost:5000/_content/Syncfusion.Blazor/scripts/grids-ec5227.min.js:1:54951)
    at e.setVisible (http://localhost:5000/_content/Syncfusion.Blazor/scripts/grids-ec5227.min.js:1:54324)
    at e.blazorCallback (http://localhost:5000/_content/Syncfusion.Blazor/scripts/syncfusion-blazor.min.js:1:44036)
    at e.blazorCallback (http://localhost:5000/_content/Syncfusion.Blazor/scripts/syncfusion-blazor.min.js:1:44372)
    at e.notify (http://localhost:5000/_content/Syncfusion.Blazor/scripts/syncfusion-blazor.min.js:1:43806)
    at r.notify (http://localhost:5000/_content/Syncfusion.Blazor/scripts/syncfusion-blazor.min.js:1:97904)
    at e.setVisible (http://localhost:5000/_content/Syncfusion.Blazor/scripts/grids-ec5227.min.js:1:215350)

11 Replies

RN Rahul Narayanasamy Syncfusion Team April 2, 2020 10:45 AM UTC

Hi Özgür, 

Greetings from Syncfusion. 

Query: Removing columns 

We have validated your query with the provided details and checked the reported problem by creating a sample based on your requirement. We could not reproduce the reported problem. It works fine(Column Header and content removed) without any script errors. Find the below code snippets and sample for your reference. 

@using Syncfusion.Blazor.Grids 

<SfGrid @ref="grd" DataSource="@Orders" AllowPaging="true"> 
    <GridPageSettings PageSize="5"></GridPageSettings> 
    <GridColumns> 
        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn> 
        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn> 
        <GridColumn Field=@nameof(Order.OrderDate) HeaderText=" Order Date" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Right" Width="130"></GridColumn> 
        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn> 
    </GridColumns> 
</SfGrid> 

@code{ 
    SfGrid<Order> grd; 
    . . . 
    protected override Task OnAfterRenderAsync(bool firstRender) 
    { 
        if (grd.Columns != null) 
        { 
            ((List<GridColumn>)grd.Columns).RemoveAt(2); 
            grd.RefreshColumns(); 
            grd.RefreshHeader(); 
            grd.Refresh(); 
        } 
        return Task.FromResult(0); 
    } 


If you are still facing the same problem, could you please share the below details. It will be helpful to validate and provide a better solution. 

  • Scripts referred in your application(both scripts and css).
  • Full Grid code snippets.
  • Screenshot or video demonstration of the issue.
  • Reproduce the reported problem in the provided sample if possible.

Note: You have created the same query in the incident 271343. You can follow or use the same incident for further updates(future updates). 

Regards, 
Rahul 



ÖA Özgür ALTUNSÖGÜT April 2, 2020 11:23 AM UTC

Hello,
first of all thank you for quick response.
I have added a screen shot as attached. As you can see deleted column names still remain at the right. 
Full grid code is below

@typeparam TData
@typeparam TDialog
@{
    var tool = (new List<string>() { "Search" });
}

<i class="fa fa-plus-square" style="cursor:pointer" aria-hidden="true" @onclick="OpenDialog">New</i>

<EditDialog isVisible="isVisible" T="TDialog" Id="Id" DialogClosed="DialogClosed"></EditDialog>

<SfGrid @ref="grd" DataSource="@DataSource" @ondblclick="Edit" AllowFiltering="true" Toolbar=@tool>
    <GridEvents  OnRecordDoubleClick="EditRecord" TValue="TData"></GridEvents>
</SfGrid>


and I Use script below in the _Host.cshtml file.
<script src="https://cdn.syncfusion.com/blazor/18.1.36-beta/syncfusion-blazor.min.js"></script>


Regards.

Attachment: Screen_Shot_20200402_at_14.11.31_b0941c5e.zip


RN Rahul Narayanasamy Syncfusion Team April 3, 2020 07:06 PM UTC

Hi Özgür, 

Thanks for the update. 

Based on the provided details, we suspect that you don’t want to show some of the columns in the grid at initial rendering. For this, we suggest you to use Visible property of Columns or you can use HideColumns method of the Grid. Here, we have hide a column(OrderDate) by using Visible property of Column and hide another column(Freight) by using HideColumns method of the Grid in DataBound event. You can use any one way to achieve your requirement. Find the below code snippets and sample for your reference. 

[code snippets] 
. . . 
 
<SfGrid @ref="DefaultGrid" DataSource="@Orders" Height="315"> 
    <GridEvents DataBound="DataBoundHandler" TValue="Order"></GridEvents> 
    <GridColumns> 
        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Center" Width="150"></GridColumn> 
        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name" Width="150" TextAlign="TextAlign.Center"></GridColumn> 
        <GridColumn Field=@nameof(Order.OrderDate) HeaderText="Order Date" Visible="false" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Center" Width="130"></GridColumn> 
        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Center" Width="120"></GridColumn> 
    </GridColumns> 
</SfGrid> 
 
@code{ 
 
    public string[] ColumnItems = new string[] { "Freight" }; 
 
 
    . . . 
    public void DataBoundHandler() 
    { 
        // Hide columns by its header text 
        this.DefaultGrid.HideColumns(ColumnItems); 
    } 
} 
 
 
Reference:  

If you are still wants to achieve your requirement by using the same way as you mentioned, then please get back to us.  

Regards, 
Rahul 



ÖA Özgür ALTUNSÖGÜT April 4, 2020 04:07 PM UTC

Hello,
I have already did this. But this time hidden columns loaded to DOM. Deleting columns removes from DOM. 
If I hide columns hidden columns make extra cost for bandwidth. 

Regards. 


RN Rahul Narayanasamy Syncfusion Team April 6, 2020 02:47 PM UTC

Hi Özgür, 

Thanks for the update. 

We have validated the provided details and you don’t  want to render the particular columns in grid(not to render columns in DOM). You can achieve your requirement by defining the columns by using Property binding way and change the columns definition in OnAfterRenderAsync. Find the below code snippets and sample for your reference. 

@page "/" 
@using Syncfusion.Blazor.Grids 
 
 
<SfGrid @ref="@Grid" Columns="@Cols" ID="Egrid" DataSource="@Orders" AllowFiltering="true" AllowPaging="true" Height="315"> 
</SfGrid> 
 
@code{ 
    SfGrid<Order> Grid; 
    public List<Order> Orders { get; set; } 
    List<GridColumn> Cols = new List<GridColumn>(); //columns bounded to Grid. 
 
    protected override void OnInitialized() 
    { 
        //initially defined 4 columns 
        Cols.Add(new GridColumn() { Field = "OrderID", HeaderText = "ID", Width = "75" }); 
 
        Cols.Add(new GridColumn() { Field = "CustomerID", HeaderText = "Name", Width = "200", Filter = new { @operator = "contains" } }); 
        Cols.Add(new GridColumn() { Field = "Freight", HeaderText = "H Text", Width = "100" }); 
        Cols.Add(new GridColumn() { Field = "OrderDate", HeaderText = "Date", Width = "100" }); 
 
        Orders = Enumerable.Range(1, 75).Select(x => new Order() 
        { 
            . . ., 
       }).ToList(); 
    } 
 
    protected override Task OnAfterRenderAsync(bool firstRender) 
    { 
        Cols = new List<GridColumn>(); //redefine the colums.   //defined only two columns 
        Cols.Add(new GridColumn() { Field = "OrderID", HeaderText = "ID", Width = "75" }); 
        Cols.Add(new GridColumn() { Field = "CustomerID", HeaderText = "Name", Width = "200", Filter = new { @operator = "contains" } }); 
        Grid.Columns = Cols;   //assigned new columns to Grid columns 
        return Task.FromResult(0); 
    } 
} 


Please get back to us if you need further assistance. 

Regards, 
Rahul 
 



ÖA Özgür ALTUNSÖGÜT April 10, 2020 06:32 AM UTC

Hello,
This is a different solution than I thought, but It works. 
Thank you so much.



RN Rahul Narayanasamy Syncfusion Team April 13, 2020 04:36 AM UTC

Hi Özgür, 

Thanks for the update. 

We are happy to hear that the provided solution helps to achieve your requirement. Please get back to us if you need further assistance. 

Regards, 
Rahul 



MM Mark McCray October 1, 2021 07:08 PM UTC

This code generates a BL0005 Error. 

We are facing the same problem. We have many columns for the users to choose from, but by including them with "Visible=False" we are having performance issues caused by the DOM including the non-visible columns. 

Instead, we would like to be able to dynamically create the columns based on customer settings.  This solution is almost there, but you are not allowed to create a GridColumn in code because of the BL0005 error. 

Do you have any other possible solutions?




RN Rahul Narayanasamy Syncfusion Team October 4, 2021 12:34 PM UTC

Hi Mark, 

Greetings from Syncfusion. 

Query: This code generates a BL0005 Error. 

We have validated your query and we suggest you to use pragma warning disable and restore, to resolve the warning errors. Refer the below code example.  

protected override void OnInitialized() 
    { 
        #pragma warning disable BL0005       // you can resolve the warning by using this 
        Cols.Add(new GridColumn() { Field = "OrderID", HeaderText = "ID", Width = "75" }); 
 
        Cols.Add(new GridColumn() { Field = "CustomerID", HeaderText = "Name", Width = "200" }); 
        Cols.Add(new GridColumn() { Field = "Freight", HeaderText = "H Text", Width = "100" }); 
        Cols.Add(new GridColumn() { Field = "OrderDate", HeaderText = "Date", Width = "100" }); 
        #pragma warning restore BL0005       // you can resolve the warning by using this 
 
        . . . 
    } 

Please get back to us if you have any concerns. 

Regards, 
Rahul 



MA Madjid November 5, 2023 03:24 PM UTC

Hi,

How may I add or remove a column by different screen size . for example show a column if screen is bigger than md.

thanks



PS Prathap Senthil Syncfusion Team November 6, 2023 12:26 PM UTC

Hi Madjid,

Query:” How may I add or remove a column by different screen size”

We recommend using MediaQuery component to dynamically adjust column visibility in the grid based on different screen sizes. Please refer to the code snippet and sample below for reference.

 

<SfMediaQuery @bind-ActiveBreakpoint="@activeBreakpoint"></SfMediaQuery>

 

<SfGrid @ref="@Grid" Columns="@Cols" ID="grid" DataSource="@Orders" AllowFiltering="true" AllowPaging="true" Height="315">

</SfGrid>

 

 

@if (activeBreakpoint == "Large")

{

    AddandRemoveColumn();

}

else if (activeBreakpoint == "Small")

{

    AddandRemoveColumn();

}

 

@code

{

 

    private string activeBreakpoint;

 

    SfGrid<Order> Grid;

    public List<Order> Orders { get; set; }

    List<GridColumn> Cols = new List<GridColumn>(); //columns bounded to Grid.

 

 

    public void AddandRemoveColumn()

    {

        Cols.RemoveAt(1);

        Cols.Add(new GridColumn() { Field = "OrderDate", HeaderText = "Date", Width = "100" });

        Grid.Refresh();

     

    }

 

 

 

}


Sample Link:
https://blazorplayground.syncfusion.com/embed/BZBUMsZnqlOOmSjd?appbar=true&editor=true&result=true&errorlist=true&theme=bootstrap5

Reference:
https://blazor.syncfusion.com/documentation/media-query/break-points


Regards,
Prathap S


Loader.
Up arrow icon