Example grid insert after / before selected row

by OnaBai

HTML

<link rel="stylesheet" href="http://cdn.kendostatic.com/2013.2.716/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2013.2.716/styles/kendo.default.min.css">
<script src="http://cdn.kendostatic.com/2013.2.716/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.2.716/js/kendo.all.min.js"></script>
<script src="http://demos.kendoui.com/content/shared/js/people.js"></script>
<button id="before" class="k-button">Insert Before</button>
<button id="after" class="k-button">Insert After</button>
<div id="grid"></div>

CSS

#grid {
    width : 490px;
}

JavaScript

var ds = {
    data    : createRandomData(20),
    pageSize: 5,
    schema  : {
        model: {
            fields: {
                Id       : { type: 'number' },
                FirstName: { type: 'string' },
                LastName : { type: 'string' },
                City     : { type: 'string' }
            }
        }
    }
};

var grid = $("#grid").kendoGrid({
    dataSource: ds,
    editable  : true,
    pageable  : true,
    selectable: true,
    columns   :
    [
        { field: "FirstName", width: 90, title: "First Name" },
        { field: "LastName", width: 200, title: "Last Name" },
        { field: "City", width: 200 }
    ]
}).data("kendoGrid");

$("#before").on("click", function() {
    var grid = $("#grid").data("kendoGrid");
    // Get selected item
    var sel = grid.select();
    var sel_idx = sel.index(); 
    // Get the item
    var item = grid.dataItem(sel);
    // Get the index in the DataSource (not in current page of the grid)
    var idx = grid.dataSource.indexOf(item);
    // Insert element before
    grid.dataSource.insert(idx, { LastName: "Smith", FirstName: "John", City: "Baiona" });
    grid.editRow($("#grid tr:eq(" + ( sel_idx + 1) + ")"));    
});

$("#after").on("click", function() {
    var grid = $("#grid").data("kendoGrid");
    // Get selected item
    var sel = grid.select();
    var sel_idx = sel.index(); 
    // Get the item
    var item = grid.dataItem(sel);
    // Get the index in the DataSource (not in current page of the grid)
    var idx = grid.dataSource.indexOf(item);
    // Insert element before
    grid.dataSource.insert(idx + 1, { LastName: "Smith", FirstName: "John", City: "Baiona" });
    grid.editRow($("#grid tr:eq(" + ( sel_idx + 2) + ")"));    
});