I have a Telerik MVC Grid in which say, there are like two fields
CustomerID
and OrdersQuantity (can go negative)
MY grid looks lik
There are two ways to accomplish this, one for server binding and the other for ajax binding.
Just a quick note: I created a model called "SmallItem" which just has to properties, CustomerID and OrdersQuantity (both int), so if any references are made to SmallItem you know where it's coming from.
Server:
This can all be achieved with just the declaration of the Telerik Grid:
@model IEnumerable<SmallItem>
@{Html.Telerik().Grid(Model)
.Name("TestGrid")
.Columns(columns =>
{
columns.Template(@<text>@(item.OrdersQuantity < 0 ? item.CustomerID.ToString() + "*" : item.CustomerID.ToString())</text>).Title("CustomerID");
columns.Bound(s => s.OrdersQuantity).Title("Order Quantity");
})
.CellAction(cell =>
{
if(cell.Column.Title == "CustomerID")
{
SmallItem item = cell.DataItem;
if(item.OrdersQuantity < 0)
{
cell.HtmlAttributes["style"] = "color: red;";
}
}
})
.Render();
}
As you can see above I'm taking use of a Template column and, using Razor syntax, simply setting up a simple if-statement to add the "*" next to the CustomerID field. Now, a really easy way to change the attributes of a cell (and not an entire row) is to hook into the CellAction function, which will execute for every cell. Having a simple if-statement here to ensure that we are in the CustomerID column (note the usage of Title as opposed to Member since this is a template column) and then you can just check what the particular instance of the Model has for an OrdersQuantity. If it's less than 0 just add the style to the HtmlAttributes collection.
Ajax:
The ajax approach involves using some JavaScript and everything can be covered in a couple of lines. If my grid looks like this:
@{Html.Telerik().Grid<SmallItem>()
.Name("AjaxTestGrid")
.Columns(columns =>
{
columns.Bound(s => s.CustomerID).Title("Customer ID");
columns.Bound(s => s.OrdersQuantity).Title("Order Quantity");
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Test", "Grid"))
.ClientEvents(clientEvents => clientEvents.OnRowDataBound("onRowDataBound"))
.Render();}
I can then take advantage of the OnRowDataBound event, which fires for every row. If I use this JavaScript:
function onRowDataBound(e) {
if (e.dataItem.OrdersQuantity < 0) {
e.row.cells[0].innerHTML += "*";
e.row.cells[0].style["color"] = "red";
}
}
I simply check the row's dataItem (only contains CustomerID and OrdersQuantity) to see if our OrdersQuantity is less than 0, then I just access the innerHTML and style collection of the particular cell (since CustomerID is the first column, it is at index 0).
Both approaches accomplish what you're looking for, which one you implement just depends on how you are binding your Grid.