New to Kendo UI for jQuery? Download free 30-day trial

Dynamically Add and Remove Columns to the Grid

Environment

Product Progress® Kendo UI® Grid for jQuery

Description

How can I add and remove columns to the jQuery Grid component dynamically?

Solution

The most straightforward way to achieve the desired scenario is to have hidden columns and allow the users to unhide them with the help of the column menu.

An alternative option is to use the setOptions() method with a custom UI, for example, a Kendo UI for jQuery MultiSelect that holds a collection of all the available columns:

  1. In the change event handler of the MultiSelect, get the current selection with the value() method.
  2. Call the setOptions() method of the Grid with the selected items.
    <label for="multiselect">Select Columns to display</label>
    <input id="multiselect" style="width:50%" />
    <div id="grid"></div>
    <script>
      var columns = [{
        field:"OrderID",
        filterable: false,
        width: 70
      },{
        field: "Freight",
        width: 70
      },{
        field: "ShipName",
        title: "Ship Name",
        width: 150
      }, {
        field: "ShipCity",
        title: "Ship City",
        width:300
      }];

      $("#multiselect").kendoMultiSelect({
        dataTextField:"field",
        dataValueField:"field",
        dataSource: {
          data: columns
        },
        value:["OrderID", "Freight", "ShipName", "ShipCity"],
        change: function(e){
          var cols = this.value();
          var grid = $("#grid").data("kendoGrid");
          grid.setOptions({columns:cols});          
        }
      });

      $("#grid").kendoGrid({
        dataSource: {
          type: "odata",
          transport: {
            read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
          },
          schema: {
            model: {
              fields: {
                OrderID: { type: "number" },
                Freight: { type: "number" },
                ShipName: { type: "string" },
                ShipCity: { type: "string" }
              }
            }
          },
          pageSize: 20,
          serverPaging: true,
          serverFiltering: true,
          serverSorting: true
        },
        height: 550,
        filterable: true,
        sortable: true,
        pageable: true,
        columns: columns
      });
    </script>

See Also

In this article