开发者

Change color based on value

开发者 https://www.devze.com 2023-01-07 00:54 出处:网络
I have a number of fields where I want to display the data in red if it is expired. <%= Html.Encode(String.Format(\"{0:d}\", Model.Subcontract.insurance_GL))%>

I have a number of fields where I want to display the data in red if it is expired.

<%= Html.Encode(String.Format("{0:d}", Model.Subcontract.insurance_GL))%>

If the date is less than today's date, then 开发者_StackOverflow中文版I'd want it to display in red. What is the best way to do this?

EDIT This is for my Detail View. It's not in a grid. It's just a listing of the fields for the individual Subcontract. There's, insurance_GL, insurance_AL, insurance_WC, etc. Different fields, not the same field repeating in a grid.


I would add a class to the field if the value is less than zero.

So I'm not sure what types of HTML elements are wrapping your field values, but using your example I would do this:

<span class="<%=(Model.Subcontract.insurance_GL < 0 ? "red" : "black")%>"
  <%= Html.Encode(String.Format("{0:d}", Model.Subcontract.insurance_GL))%>
</span>


It really depends on how you are rendering your data in the client page. Are you using asp.net forms, with a GridView? Are you generating the html for your data yourself?

I usually go about this with css classes. I'll have a class for flagged items, like this:

.late
{
    color: #f00;
}

And in the code behind, where my html is being generated, if you're creating all the html yourself:

foreach(Item item in items)
{
    string cls = "";
    if (item.IsLate)
        cls = " class='late'";
    html += "<div" + cls + ">" + item.Text + "</div>";
}

That will create <div>Item1</div> for a non-late item, and <div class="late">Item2</div> for a late item. You can also have a class for non-late items, if you want them to be styled a certain way too. Easy enough.

If the items you're flagging are server controls, and you're not creating the html yourself, you can assign a class to them:

if (item1.IsLate)
    myTextBox.CssClass = "late";

If your data is bound to a GridView, you can have an event handler for RowDataBound, and do something like this:

protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Item item = e.Row.DataItem as Item;
        if (item.IsLate)
            e.Row.CssClass = "late";
    }
}

You could also apply the styling to an individual cell in the GridView:

// 3rd cell
e.Row.Cells[2].CssClass = "late";

Hope one of these fits your scenario.

0

精彩评论

暂无评论...
验证码 换一张
取 消