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

How to add grid columns dynamically

Environment

Product Progress Kendo UI Grid

Description

I need to add columns dynamically. What are my options?

Solution

  1. The simplest option is to have hidden columns and allow the users to unhide them with the help of the column menu.
  2. Another option could be to use the setOptions() method with a custom UI, for example a Kendo UI MultiSelect that holds a collection of all the available columns.
    1. In the MultiSelect change event handler, get the current selection with the value() method
    2. Call the grid setOptions() method 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
Not finding the help you need? Improve this article