How to add row number to kendo ui grid?

天涯浪子 提交于 2019-11-28 23:37:19

Initialize a variable and show it in column as template: "#= ++record #"

Working Demo

Here is code:

var record = 0;

$("#grid").kendoGrid({
  dataSource: {
    data: [{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" }, { foo: "foo" }, { foo : "foo1" }],
    pageSize: 10
  },
  sortable: true,
  columns: [ {
    title: " ",
    template: "#= ++record #",
    width: 30
  }, { field: "foo" }],
  pageable: true,
  dataBinding: function() {
    record = (this.dataSource.page() -1) * this.dataSource.pageSize();
  }
});

For Razor you also need to actually show the number also: (not enough point thingies to comment)

above the grid:

@{int counter = 1;}

inside column definitions:

columns.Template(@<text> 
        <span>@counter @{ counter++; }</span>
        </text>).Title("#");
Ehsan Mirsaeedi

there is no need to define any variables, you can get help from databound event:

$("#grid").kendoGrid({
    sortable: true,
    dataSource: [{
        name: "Jane Doe",
        age: 30
    }, {
        name: "John Doe",
        age: 33
    }],
    columns: [{
        field: "name"
    }, {
        field: "age"
    }, {
        field: "rowNumber",
        title: "Row number",
        template: "<span class='row-number'></span>"
    }],
    dataBound: function () {
        var rows = this.items();
        $(rows).each(function () {
            var index = $(this).index() + 1 
            + ($("#grid").data("kendoGrid").dataSource.pageSize() * ($("#grid").data("kendoGrid").dataSource.page() - 1));;
            var rowLabel = $(this).find(".row-number");
            $(rowLabel).html(index);
        });
    }
});
J Lipford

YD1m's template did not work for me it treated the variable like a string. So I had to implement it like so:

columns.Template(@<text>@((long)counter++)</text>)

For asp.net mvc wrapper you should use something like this:

@{
     var counter = 1;
}

@( Html.Kendo().Grid<Types>()
   .Name("grid")
   .Columns(columns =>
   {           
        // Define a template column with row counter
       columns.Template(@<text>@counter++</text>);    

       // Define a columns from your data set and set a column setting
       columns.Bound(type => type.id);    

       columns.Bound(type=> type.name).Title("Name");    
       // add more columns here          
   })
)

Based on Ehsan Mirsaeedi's great answer, I came up with this version, which assigns indices starting at 0 instead of row numbers starting at 1, skips group headers if the grid is grouped, and handles the case when the grid is not paged.

I needed these indices in order to add a template with a hidden input to each column, so that I can then submit the grid's values along with the entire form.

I think it's related enough and worth adding to the thread...

Code:

var theGrid = $("#grid").data("kendoGrid");
var rows = this.items().filter(function (index, item) {
    return $(item).hasClass("k-grouping-row") == false;
});

$(rows).each(function () {
    var index = $(this).index();

    //prevent group header rows from incrementing index
    if (theGrid.dataSource.options.group != null && theGrid.dataSource.options.group.length > 0)
        index -= $(this).prevAll("#grid tr.k-grouping-row").length;

    //adjust indices for current page
    if (theGrid.options.pageable == true)
        index += theGrid.dataSource.pageSize() * (theGrid.dataSource.page() - 1);

    //add the value to the grid's data object
    theGrid.dataItem(this).rowNumber = index;

    //and update the grid's HTML
    var rowLabel = $(this).find(".row-number");
    $(rowLabel).html(index);
});

Result:

If you need, row number in editable grid

    $(document).ready(function(){
        $("#grid").kendoGrid({
        dataSource: {
            data: null,
            schema: {
                model: {
                    id: "register_No",
                    fields: {
                        register_No: {editable: true},
                        myEditableField: {editable: true},
                    }
                }
            }

        },
        edit:function(e){
            var fields= $('input[name="register_No"]');
            fields.attr('disabled', true);
            fields.removeClass('k-input k-textbox');
            fields.addClass('none');
//create this class and set border and background none
            $('input[name="myEditableField"]').focus();
        },
        save:function(e){
            var total=e.sender.dataSource.data().length;
            if(e.model.register_No==""){
                e.model.register_No=total;
            }

        },
        remove:function(e){
            var grid = $("#grid").data("kendoGrid");
            var todos=grid.dataSource.data();
            var id_actual=e.model.register_No;
            var count=1;
            for(var i=0;i<todos.length;i++){
                if(todos[i].register_No!==id_actual){
                    var data = grid.dataSource.at(i);
                    data.set("register_No", count);
                    count++;

                }
            }
        }
        , height: 280,
        toolbar: ["create"],
        scrollable: true,
        editable: {mode:"inline",    createAt: "bottom",     confirmation: true
        }
        ,
        columns: [
            {field: "register_No",title: "No", width: 30},
            {field: "myEditableField", title: "Any Field", width: 120},
            {field: "options", command: ["edit", "destroy"], width: 200}

        ]
    });
        });
<div id="grid"></div>

Declare a variable for row counting:

var rowNumber = 0;

Use it in your template with ++ operator to increment it for each iteration:

#= ++rowNumber #

This also works for Kendo UI ListView.

See the official document:

http://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Templates/add-row-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!