To implement row selection via checkbox in Wijmo Gridview server control, you can add a checkbox control in Template column and then handle the RowCreated event. But, in WijGrid widget, there is a different way for achieving the same requirement. In this blog, we will see how we can have Checkbox row selection in Wijgrid widget. To start with, create a table tag converted into a Wijmo Gridview widget as demonstrated in the Online Demo. Now, add a checkbox column in the columns collection and handle its CellFormatter method so that the particular row can be added in the Selection object when checkbox is clicked. Here is the code for same:
columns: [
{ dataType: "number", headerText: "Number" },
{ headerText: "Nationality" },
{ headerText: "Player" },
{ headerText: "Position" },
{
//add the checkbox column
headerText: "<input type=\\"checkbox\\" class=\\"mycb\\" onclick=\\"toggleSelection(event, this,
'demo')\\" />",
cellFormatter: function (args) {
if (args.row.type & $.wijmo.wijgrid.rowType.data) {
args.$container
.empty()
.append(
$("<input type='checkbox' class='mycb' />")
.click(function (e) {
e.stopPropagation();
})
.change(function (e) {
//add the row if checkbox is selected
if (e.target.checked) {
$("#demo").wijgrid("selection").addRows(args.row._dataTableRowIndex);
} else {
$("#demo").wijgrid("selection").removeRows(args.row._dataTableRowIndex);
}
})
);
return true;
}
}
}
]
Sometimes, there could be a requirement where users would like to Select/Clear all rows with header checkbox. In order to achieve this, you can handle the onclick event of the header checkbox and use the selectAll/clear methods of Selection object of Wijgrid widget. The code will look like:
function toggleSelection(e, sender, id) {
e.stopPropagation();
//select/unselect all rows on basis of checkbox
if (sender.checked) {
$("#" + id).wijgrid("selection").selectAll();
} else {
$("#" + id).wijgrid("selection").clear();
}
}
Following image shows the final appearance of Wijmo Gridview after implementing the above code You may download a complete sample implementing the same. Note: In newer version i.e. 2014 or later, WijGrid listens to focusin events of child controls, along with the click event. So, you would need to add focus event handler to checkbox the same way you do it for click event, to select multiple rows, when the user checks the checkbox. Refer to this sample implementing checkbox selection with Paging in WijGrid