How to set background color of cell bases on a value with NonFactors MVC6 Gridview

156 Views Asked by At

I'm trying to set background color for cell based on a value. But i cannot determine how to achieve it. I Can change cell value but not background value. I use MVC6 NonFactors Gridview.

Any help will be appreciated.

When i use : Columns[index].CssClasses="MyClass" it update with the same color for all values of the column .

1

There are 1 best solutions below

0
On

Below is a sample use of the grid. This grid has one column "LogType" and we will show how to format the cell and the row. The column will contain labels in this sample but we could any element. Notice that a string expression is attached for identification "errortype".

@(Html.Grid(Model.Results)
    .Build(columns =>
    {
        columns.Add(model => Html.Label("errortype",model.ErrorType)).Titled("Type");


    })
    .Using(GridFilterMode.Header)
    .Empty("No data found")
    .Filterable()
    .Sortable()
)

The javascript below will grab all the cells (td) and format the row background color accordingly...

$(document).ready(function() {

    var types = document.querySelectorAll("[for^='errortype'");
    var i;
    for (i = 0; i < types.length; ++i) {

        switch (types[i].textContent) {
            case 'Warning':
            types[i].parentNode.parentNode.style.backgroundColor = 'lightyellow';
                break;

            case 'Error':
            types[i].parentNode.parentNode.style.backgroundColor = 'pink';
                break;
        }
    }
});

Note: types[i] is the "lable" node and types[i].parentNode is the "td" node and types[i].parentNode.parentNode is the "tr" node. You can set styles and formats as needed...