Articles in this section
Category / Section

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

4 mins read

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

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied