)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Essential JS2

Syncfusion jQuery based widgets are no longer in active development. Switch to our pure JavaScript based next generation Essential JS 2 library.

Syncfusion Feedback

How to get selected records from all page in multi checkbox feature?

Platform: jQuery |
Control: ejGrid |
Published Date: March 31, 2017 |
Last Revised Date: May 12, 2020

This knowledge base explains how to get the selected Records from all the pages in grid when using checkbox selection.

We can get array of selected record index value with corresponding page information from the variable checkSelectedRowsIndexes of the Grid. Using the selected record index from that variable, we can get the selected records from model.dataSource (dataSource bound to the Grid).

The checkSelectedRowsIndexes is a collection which holds the page Index and the selected record index of the corresponding page.  

 

HTML

<input type="button" id="GetRecords" />
 
<div id="Grid"></div>

 

JS

<script type="text/javascript">
    $(function () {
 
        $("#GetRecords").ejButton({
            text: "Get selected Records",
            click: "getSelectedRecords"
        })
 
        $("#Grid").ejGrid({
            dataSource: window.gridData,
            allowPaging: true,
            allowGrouping: true,
            allowFiltering: true,
            pageSettings: { pageSize: 4 },
            filterSettings: {
                filteredColumns: [
                    {
                        "field": "CustomerID", "operator": "startswith", "value": "vi",
                        "matchcase": false, "predicate": "and"
                    }]
            },
            groupSettings: { groupedColumns: ["EmployeeID"], showDropArea: false },
            columns: [
                    { type: "checkbox", width: 50 },
                    { field: "OrderID", headerText: "Order ID", width: 75 },
                    { field: "CustomerID", headerText: "Customer ID", width: 80 },
                    { field: "EmployeeID", headerText: "Employee ID", width: 75 },
                    { field: "ShipCity", headerText: "Ship City", width: 110 }
            ]
        });
    });
</script>

 

RAZOR:

@Html.EJ().Button("GetRecords").Text("Get selected Records").ClientSideEvents(e => e.Click("getSelectedRecords"))
 
@(Html.EJ().Grid<object>("Grid")
      .Datasource((IEnumerable<object>)ViewBag.datasource)
      .AllowPaging()
      .AllowGrouping()
      .AllowFiltering()
      .GroupSettings(grp =>
      {
          grp.GroupedColumns(gCols => gCols.Add("EmployeeID"));
          grp.ShowDropArea(false);
      })
      .FilterSettings(filter => filter.FilteredColumns(fcols => {
          fcols.Field("CustomerID");
          fcols.Value("vi");
          fcols.Operator(FilterOperatorType.StartsWith);
          fcols.Predicate("and");
          fcols.MatchCase(false);
       }))
      .PageSettings(page=>page.PageSize(4))
      .Columns(col =>
          {
              col.Type("checkbox").Width(50).Add();
              col.Field("OrderID").HeaderText("Order ID").Width(75).Add();
              col.Field("CustomerID").HeaderText("Customer ID").Width(80).Add();
              col.Field("EmployeeID").HeaderText("Employee ID").Width(75).Add();
              col.Field("ShipCity").HeaderText("Ship City").Width(110).Add();
          })
)
 

 

C#

namespace Sample.Controllers
{
    public class GridController : Controller
    {
        public ActionResult GridFeatures()
        {
            ViewBag.datasource = new NorthwindDataContext().OrdersViews.ToList();
            return View();
        }
    }
}

 

ASPX

    <ej:Button id="GetRecords" runat="server" Text="Get selected Records" Type="Button" ClientSideOnClick="getSelectedRecords" />
 
    <ej:Grid id="Grid" runat="server" AllowGrouping="true" AllowFiltering="true" Allowpaging="true" >
        <PageSettings PageSize="4" />
        <GroupSettings  GroupedColumns="EmployeeID" ShowDropArea="false"></GroupSettings>  
        <Columns>
            <ej:Column type="checkbox" width="50" />
            <ej:Column Field="OrderID" HeaderText="Order ID" width="75" />
            <ej:Column Field="CustomerID" HeaderText="Customer ID" width="80" />
            <ej:Column Field="EmployeeID" HeaderText="Employee ID" width="75" />
            <ej:Column Field="ShipCity" HeaderText="Ship City" width="110"/>
        </Columns>
    </ej:Grid>

 

namespace sqlbinding
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Grid.FilterSettings.FilteredColumns = new List<FilteredColumn>() { new FilteredColumn() {
                Field="CustomerID", MatchCase=false, 
                Operator= FilterOperatorType.StartsWith, 
                Predicate="and",
                Value="vi"
            } };
            this.Grid.DataSource = new NorthWndDBDataContext().Orders.ToList();
            this.Grid.DataBind();
        }
    }
}

 

.Net Core

@using Syncfusion.JavaScript;
@using Syncfusion.JavaScript.Models;
 
@{
    var GroupedCols = new List<string>() { "CustomerID" };
     
    var filteredCols = new List<FilteredColumn>(){ new FilteredColumn()
    {
        Field = "CustomerID",
        MatchCase = false,
        Operator = FilterOperatorType.StartsWith,
        Value = "vi",
        Predicate = "and"
    }
    };
}
 
<ej-button id="GetRecords" text="Get selected Records" click="getSelectedRecords"/>
 
<ej-grid id="Grid" allow-paging="true" datasource="ViewBag.datasource" allow-filtering="true" allow-grouping="true">
    <e-group-settings grouped-columns="GroupedCols" show-drop-area="false"/>
    <e-filter-settings filtered-columns="filteredCols"/>
    <e-page-settings page-size="4"/>
    <e-columns>
        <e-column type="checkbox" width="50"></e-column>
        <e-column field="OrderID" header-text="Order ID" width="75" ></e-column>
        <e-column field="EmployeeID" header-text="Employee ID" width="80" ></e-column>
        <e-column field="CustomerID" header-text="Customer ID" width="75" ></e-column>
        <e-column field="Freight" header-text="Ship City" width="110"></e-column>
    </e-columns>
</ej-grid>

 

namespace core1.Controllers
{
    public partial class GridController : Controller
    {
        public static List<Orders> order = new List<Orders>();
        public ActionResult GridFeatures()
        {
            ViewBag.dataSource = order;
            return View();
        }
    }
}
 

 

Angular2:

<input type="button" ej-button id="GetRecords" value="text" (click)="getSelectedRecords($e)" />
 
<ej-grid id="Grid" #grid  [allowPaging]="true" [allowGrouping] ="true" allowFiltering="true" pageSettings]="pager" [groupSettings]="grpSettings" filterSettings="filterSettings" [dataSource]="datasrc" >
    <e-columns>
        <e-column type="checkbox" width="50"></e-column>
        <e-column field="OrderID" headerText="Order ID" width="75"></e-column>
        <e-column field="CustomerID" headerText="Customer ID" width="80"></e-column>
        <e-column field="EmployeeID" headerText="Employee Name" textAlign="right" width="75"></e-column>
        <e-column field="ShipCity" headerText="Ship City" width="110"></e-column>
    </e-columns>
</ej-grid>

 

TypeScript:

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { EJComponents } from "ej-angular2/src/ej/core";
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    constructor() {
        this.grpSettings = { groupedColumns: ["EmployeeID"], showDropArea: false };
        this.pager = { pageSize: 4 };
        this.filterSettings = {
            filteredColumns: [
                {
                    "field": "CustomerID", "operator": "startswith", "value": "vi",
                    "matchcase": false, "predicate": "and"
                }]
        };
        this.text = "Get selected Records";
        this.datasrc = data;
    }
    public datasrc: any;
    public grpSettings: any;
    public pager: any;
    public filterSettings: any;
    public text: any;
    @ViewChild('grid') Grid: EJComponents<any, any>;//
 
}
 

 

We can get the selected record details in button click event after selecting all the records using checkbox selection.

This will work only for the local data and not for the remote data. Since Grid will not aware of the other page records in the remote dataSource, it loads current data alone while pagination. If any other actions such as sorting, filtering, grouping has be taken place, we cannot get the selected records from the Grid dataSource.

<script type="text/javascript">
    function getSelectedRecords(args) {
        var obj = $("#Grid").ejGrid("instance"), rec = [];
        var check = obj.checkSelectedRowsIndexes;  // collection which holds the page index and the selected record index
        if (check.length) {
            for (var pageInx = 0; pageInx < check.length; pageInx++) {
                if (!ej.isNullOrUndefined(check[pageInx]))
                    rec = getRecords(pageInx, check[pageInx], obj, rec);
            }
        }
        console.log(rec);
    }
    function getRecords(pageInx, inx, proxy, rec) {
        var data = proxy.model.dataSource;
        var cloneQuery = proxy.model.query.clone(), newQuery = cloneQuery.clone(), del = [];
        cloneQuery.queries.filter(function (q, ix) {
            if (q.fn == "onPage" || q.fn == "onGroup") del.push(ix);
        })
        for (var i = del.length - 1; i >= 0; i--) {
            newQuery.queries.splice(del[i], 1);
        }
        data = (data instanceof ej.DataManager) ? data.dataSource.json.slice(0) : data.slice(0);
        data = ej.DataManager(data).executeLocal(newQuery).result;
 
        if (inx.length) {
            for (var i = 0; i < inx.length; i++) {
                var pageSize = proxy.model.pageSettings.pageSize;//gets the page size of grid
                var dat = data[pageInx * pageSize + inx[i]];
                rec.push(dat);     //pushing all the selected Records
            }
        }
        return rec;
    }
</script>

 

TypeScript:

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { EJComponents } from "ej-angular2/src/ej/core";
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    constructor() {
    }
    @ViewChild('grid') Grid: EJComponents<any, any>;//
 
    getSelectedRecords(args) {
        var rec = [], check = this.Grid.widget.checkSelectedRowsIndexes;
        // collection which holds the page index and the selected record index
        if (check.length) {
            for (var pageInx = 0; pageInx < check.length; pageInx++) {
                if (!ej.isNullOrUndefined(check[pageInx]))
                    rec = this.getRecords(pageInx, check[pageInx],rec);
            }
        }
        console.log(rec);
    }
    getRecords(pageInx, inx, rec) {
        var data = this.Grid.widget.model.dataSource;
        var cloneQuery = this.Grid.widget.model.query.clone(), newQuery = cloneQuery.clone(), del = [];
        cloneQuery.queries.filter(function (q, ix) {
            if (q.fn == "onPage" || q.fn == "onGroup") del.push(ix);
        })
        for (var i = del.length - 1; i >= 0; i--) {
            newQuery.queries.splice(del[i], 1);
        }
        data = (data instanceof ej.DataManager) ? data["dataSource"].json.slice(0) : data.slice(0);
        data = new ej.DataManager(data).executeLocal(newQuery)["result"];
 
        if (inx.length) {
            for (var i = 0; i < inx.length; i++) {
                var pageSize = this.Grid.widget.model.pageSettings.pageSize;  //gets the page size of grid
                var dat = data[pageInx * pageSize + inx[i]];
                rec.push(dat);//pushing all the selected Records
            }
        }
        return rec;
    }
}
 

 

Checkbox Selection

Figure: Grid with selection and selected records of all the page in console

 

Sample Demo: http://jsplayground.syncfusion.com/db0pbnak

ADD COMMENT
You must log in to leave a comment
Comments
Sunil patra
Jan 16, 2018

error :  ejGrid: methods/properties can be accessed only after plugin creation

pls help!!!

Reply
Mani Sankar Durai [Syncfusion]
Jan 17, 2018

Hi Sunil,

 

We have checked your query and we suspect that the cause of the issue is that you have created a grid instance in the document ready before the Grid control get rendered. So please ensure to create an instance after grid control has rendered.

If you still face the issue please get back to us with the following details.

1.       Share the full grid code that you have used.

2.       If possible please share the sample with issue reproducing.

The provided information will help us to analyze the issue and provide you the response as early as possible

 

Regards,

Manisankar Durai.

Reply
Sunil patra
Jan 18, 2018

typescript/////

ngOnInit() {
this.fetchClientList();
this.commands = [{
type: 'delete',
buttonOption: {
iconCss: ' e-icons e-delete',
cssClass: 'e-flat',
click: this.onClick
}
}];
console.log('grid object' + this.grid);
}
public onClick(this) {
console.log(this);
let grid = $('#grid').ejGrid('instance');
let index = $('#grid').element.closest('tr').index();
let record = $('#grid').getCurrentViewData()[index];
alert('Record Details: ' + JSON.stringify(record));
}


html/////
<ej-grid id='grid' [dataSource]='clientData' [allowSorting]='true' [selectionSettings]='selectOptions' (rowSelected)="onRowSelected($event)"
(dataBound)="dataBound()">
<e-columns>
<e-column field='clientName' headerText='NAME' width='150' textAlign="left">e-column>
<e-column field='companies.name' headerText='COMPANY' width='50' textAlign="left">e-column>
<e-column field='station' headerText="STATION" width='40' textAlign="left">e-column>
<e-column field='formats.length' headerText='FORMAT' width='20' textAlign="right">e-column>
<e-column headerText='Manage Records' width='40' [commands]='commands'>e-column>
e-columns>
ej-grid>

Reply
Sunil patra
Jan 18, 2018

this produces the above issue


Mani Sankar Durai [Syncfusion]
Jan 18, 2018

Hi Sunil,

 

We have checked the reported issue with the provided code example and we are not able to reproduce the reported issue.

We have also prepared a sample based on the provided code example and that can be available from the below link

Link: http://www.syncfusion.com/downloads/support/directtrac/196682/ze/angular2-seeds-systemjs508964927

We have also found that you have called getCurrentViewData() using grid element instead of getting from grid instance. We suggest you to modify the code as like below

 

public onClick(e: any) {

        console.log(e);

        var grid = $('#grid').ejGrid('instance');

        var index = grid.getSelectedRows().closest("tr").index()

        var record = grid.getCurrentViewData()[index];

        alert('Record Details: ' + JSON.stringify(record));

    }

 

Also we found that you are trying to get the selectedRecords in grid. To get the selected records we suggest you to use getSelectedRecords method in grid.

Link: https://help.syncfusion.com/api/angular/ejgrid#methods:getselectedrecords

If you still face the issue please provide the sample with issue reproducing.

 

Regards,

Manisankar Durai.

Reply
Sunil patra
Jan 19, 2018

after implementing ur code , i still got the error :  ejGrid: methods/properties can be accessed only after plugin creation

Mani Sankar Durai [Syncfusion]
Jan 19, 2018

Hi Sunil

 

Before proceeding please provide us the following details.

1.      Share the video demonstration of the reported issue that you have faced.

2.      Share the stack trace of the issue from the console window.

3.      You have called a method fetchClientList in ngOnInit. Share the code that you have used in fetchClientList method.

4.      Share the sample with issue reproducing.

The provided information will help us to analyze the issue and provide you the response as early as possible

 

Regards,

Manisankar Durai.

Reply

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon