How to Filter Null Values in a Nullable Boolean Grid Column
Environment
| Product Version | 2022.2.621 |
| Product | Grid for ASP.NET MVC |
Description
When you filter a nullable Boolean Grid column for false, rows with a null value are not included. You can also display null values as false and change the Boolean filter-menu labels.
Cause
A filter for false does not match null, because they are distinct values. A ClientTemplate changes only the displayed cell value; it does not change the underlying value used for filtering.
Solution
The Grid model must define the column as nullable:
public bool? Processed { get; set; }
Change the Boolean Filter Labels and Display Null as False
The IsTrue and IsFalse messages apply to the Boolean filter menu. Use the default menu mode for the radio buttons; do not set Mode(GridFilterMode.Row) for this example.
Add the following configuration to the Grid:
@(Html.Kendo().Grid<ProductViewModel>()
.Name("grid")
.Columns(columns => columns
.Bound(p => p.Processed)
.ClientTemplate("#= Processed == null ? false : Processed #"))
.Filterable(filterable => filterable.Messages(messages =>
messages.IsTrue("Yes").IsFalse("No")))
.Events(events => events.Filter("onFilter"))
)
Include Null Values When Filtering for False
Handle the Grid Filter event. When the selected value for Processed is false, replace that field's filter with an or group that matches false and null. The handler accepts either a Boolean false or the string "false".
function onFilter() {
var grid = this;
setTimeout(function () {
var dataSource = grid.dataSource;
var filter = dataSource.filter();
if (filter && filter.filters) {
var processedFilters = filter.filters.filter(function (item) {
return item.field === "Processed";
});
if (processedFilters.length > 0 &&
(processedFilters[0].value === false || processedFilters[0].value === "false")) {
filter.filters = filter.filters.filter(function (item) {
return item.field !== "Processed";
});
filter.filters.push({
logic: "or",
filters: [
{ field: "Processed", operator: "eq", value: false },
{ field: "Processed", operator: "eq", value: null }
]
});
dataSource.filter(filter);
}
}
}, 0);
}
Test the Behavior
- Open the Boolean filter menu for the
Processedcolumn. The radio labels should read Yes and No. - Select No. Rows with
Processedset tofalseornullshould appear. - Select Yes. Rows with
Processedset totrueshould appear. - Confirm that null values display as
falsein the column.