This is a migrated thread and some comments may be shown as answers.

Show Hide Columns dynamically

3 Answers 2189 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Anthony
Top achievements
Rank 1
Anthony asked on 21 Sep 2013, 04:45 PM
Hi,

We were using the Kendo Grid in the following way, using JQuery. As you can see in the createTelerikGridControls method,
the columns are being created dynamically.  (ie if they should be visible or hidden).

This is done in the controller:

 public Dictionary<string, object> GetATMStatusGridData(int id, int userId, int pageId)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            object[] args;
            try
            {
                List<PPSPortal.Models.ATM> atmModelList = GetATMStatusData(id);

                List<ColumProperties> deserializedColumnProperties = GetUserPreferencesColumnProperties(userId, pageId);

                List<ColumProperties> columns = new List<ColumProperties>();
                columns.Add(new ColumProperties { field = "Id", title = "ATM Id", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "Id"), width = 40 });
                columns.Add(new ColumProperties { field = "Name", title = "Name", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "Name"), width = 60 });
                columns.Add(new ColumProperties { field = "Status", title = "Status", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "Status"), width = 30, template = "#= formatCellColor(Status) #" });
                columns.Add(new ColumProperties { field = "Active", title = "Active", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "Active"), width = 30 });
                columns.Add(new ColumProperties { field = "Online", title = "Online", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "Online"), width = 30 });
                columns.Add(new ColumProperties { field = "TotalCashRemaining", title = "Total Cash Remaining", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "TotalCashRemaining"), width = 70, template = "#= formatToatlCash(TotalCashRemaining) #" });
                columns.Add(new ColumProperties { field = "LastMessageFromATM", title = "Last Message From ATM", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "LastMessageFromATM"), width = 80 });
                columns.Add(new ColumProperties { field = "LastMessageToATM", title = "Last Message To ATM", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "LastMessageToATM"), width = 80 });
                columns.Add(new ColumProperties { field = "GroupName", title = "Group Name", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "GroupName"), width = 50 });
                columns.Add(new ColumProperties { field = "Location", title = "ATM Location", hidden = Helpers.Helper.ColumnIsHidden(deserializedColumnProperties, "Location"), width = 140 });
                dict.Add("Columns", columns);
                dict.Add("Collection", atmModelList);
            }
            catch (Exception ex)
            {

            }
            return dict;
        }

The ColumnProperties class has field, title and hidden properties which is added to the Dictionary object.
this Disctionary object stores:
1. The data (ATM)
2. Columns meta data (ColumnProperties)

In JQuery:
$(document).ready(function () {
        // Send an AJAX request
        var participantId = $("#ParticipantId").attr("value");
        var userId = $("#UserId").attr("value");
        var apiUrl = '/api/ATMStatusWebAPI/GetATMStatusGridData/' + participantId + '?userId=' + userId + '&pageId=3';
        var grid = $("#grid");
        grid.css('color', '#1e426d');
        var gridblock = $(".JHADisplayBlock_Grid");
        gridblock.hide();
        $.getJSON(apiUrl)
            .done(function (data) {
                var tbl = $(".JHADisplayBlock_Table");
                tbl.css("width", "100%");
                //GridProperties is a prototype to set the properties of the Grid
                var jhaGridProperties = new GridProperties(data.Collection, data.Columns, 20, true, true, false, true, [20, 30, 40, 50], true, true, true, true, "single row", "blue");
                createTelerikGridControls(jhaGridProperties);
                gridblock.show();
            })
        .error(function (jqXHR, textStatus, errorThrown) {
            //alert("error " + errorThrown);
            //alert("incoming Text " + jqXHR.responseText);
        })
    });

    // Create the Telerik controls
    function createTelerikGridControls(jhaGridProperties) {
        var grids = $(".JHAGrid");
        grids.each(function () {
            $(this).kendoGrid({
                dataSource: {
                    data: jhaGridProperties.data,
                    pageSize: jhaGridProperties.pageSize
                },
                color: jhaGridProperties.color,
                groupable: jhaGridProperties.groupable,
                scrollable: jhaGridProperties.scrollable,
                sortable: jhaGridProperties.sortable,
                pageable: {
                    refresh: jhaGridProperties.refreshPages,
                    pageSizes: jhaGridProperties.pageSizes
                },
                filterable: jhaGridProperties.filterable,
                selectable: jhaGridProperties.rowSelectableType,
                dataBound: addExtraStylingToGrid,
                reorderable: jhaGridProperties.reorderable,
                columnMenu: {
                    columns: jhaGridProperties.showColumns
                },
                toolbar: kendo.template($("#toolbarTemplate").html()),
                detailTemplate: kendo.template($("#template").html()),
                detailInit: detailInit,
                change: onGridClick,
                columns: jhaGridProperties.columns
            });
        });
    }


All this works fine.

Now we need to do this in ASP.Net MVC. But I am not able to hide/show the columns in the same way, as Visible needs to be hardcoded to true or false at design time
Could you please help me with this?

 @(Html.Kendo().Grid<PPSPortal.Models.ATM>()
                                  .DataSource(dataSource => dataSource
                                      .Ajax()
                                      .Read(read => read.Action("GetATMStatusGrid", "ATM", new { id = participantId, userId = userId, pageid = 3 }))
                                      .PageSize(10)
                                      .ServerOperation(false)
                                   )
                .Name("Grid")
                .Sortable()
                .Filterable()
                .Pageable()
                .ColumnMenu()
                .Columns(cols=>
               {
                         col.Bound(m => m.Id).Visible(false);
                         col.Bound(m => m.Name).Visible(true);
               })
                .Groupable()
                                    )

3 Answers, 1 is accepted

Sort by
0
Anthony
Top achievements
Rank 1
answered on 21 Sep 2013, 08:55 PM
I fixed this problem using Javascript:

function onDataBound(e) {
    //Hide show columns
    var columns = e.sender._data[0].ColumnProperties;
    var grid = $('#Grid').data('kendoGrid');
        for(i=0; i< grid.columns.length; i++)
        {
            var columnInfo = grid.columns[i];
            for(j=0; j< columns.length; j++)
            {
                if(columnInfo.field == columns[j].field)
                {
                    if(columns[j].hidden == true)
                    {
                        grid.hideColumn(i);
                    }
                }
            }
        }
    }
If anyone's got  a better way to do this, please let me know
0
Mike
Top achievements
Rank 1
answered on 17 Jun 2015, 03:42 PM

I'm looking to do something similar but looping through and hiding multiple columns is extremely slow and blocks all other processes. Has anyone come across other workarounds?

 And I've created this feature suggestion to allow showing/hiding multiple columns, if you or anyone else is interested.

0
Dimo
Telerik team
answered on 19 Jun 2015, 08:19 AM
Hello Dmitri,

Instead of showing or hiding multiple columns, which is a resource-intensive operation, you can consider using setOptions to reinitialize the Grid with the desired column visibility settings. Note that the Grid will be rebound in this case.

http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#methods-setOptions

Regards,
Dimo
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Tags
Grid
Asked by
Anthony
Top achievements
Rank 1
Answers by
Anthony
Top achievements
Rank 1
Mike
Top achievements
Rank 1
Dimo
Telerik team
Share this question
or