根据条件隐藏列菜单选项列中的列

时间:2014-04-23 02:59:40

标签: javascript kendo-ui kendo-grid

我正在使用剑道网格菜单选项用于剑道网格。我希望通过第三个选项隐藏/显示列,即列,如果该列的标题为空,则我想隐藏菜单。

enter image description here

这里我想隐藏RefValue4和RefValue5,因为它对应的值从数据库变为空。所以不需要显示它们。

我这样做:

if (grid.dataSource.data()[0].RefName4==null) {
    grid.hideColumn(18);
}

但无法达到效果。

1 个答案:

答案 0 :(得分:0)

是否足够检查网格第一行的内容(正如您在代码示例中所建议的那样??如果是这样,您可以定义一个隐藏列的dataBound处理程序:

dataBound : function (e) {
    // Get reference to the grid
    var grid = e.sender;
    // Get reference to received data
    var data = e.sender.dataSource.data();
    // Check that we actually received any data
    if (data.length > 0) {
        // Iterate on columns hiding those that in the first row have no data
        $.each(grid.options.columns, function (idx, elem) {
            if (!data[0][elem.field]) {
                grid.hideColumn(idx);
            }
        });
    }
}

这可以在您从服务器接收数据的任何时候运行,但正如我所说,只检查第一个内容,但您可以轻松修改以检查所有内容。这没有实现的是隐藏菜单中的列标题。

请在此处查看正在运行的示例:http://jsfiddle.net/OnaBai/XNcmt/67/

编辑:如果您需要不显示没有数据的列但也未显示在菜单中,则需要在没有这些列的网格中配置columns。一旦接收到数据,您就可以在运行时执行以下操作:

// Fetch data from the DataSource
ds.fetch(function (d) {
    // By default, no column in the grid
    var columns = [];
    // List of available column definitions
    var definitions = [
        { field: "Id", hidden: true },
        { field: "FirstName", title: "First Name" },
        { field: "LastName", title: "Last Name" },
        { field: "City" },
        { field: "Position" }
    ];
    // For each column in the definition check if there is data
    $.each(definitions, function(idx, elem) {
        if(d.items[0][elem.field]) {
            // If there is data then copy the definition to columns
            columns.push(elem);
        }
    });
    // Use received data plus the columns definition computed
    $("#grid").kendoGrid({
        dataSource: d.items,
        editable  : false,
        pageable  : true,
        columnMenu: true,
        columns   : columns
    }).data("kendoGrid");
});

其中dsDataSource定义。

请在此处查看:http://jsfiddle.net/OnaBai/XNcmt/69/