MMC
MMC

Reputation: 109

Comparing dates in GridDataItem cell in order to color that cell

I need to change color of a cell - which is dependent on a date - i can change color of cell no issue here

        GridDataItem item = e.Item as GridDataItem;

        **if ((item["run_Date"].Text > DateTime.Now))** //error is in this line of code
        {
            foreach (GridColumn col in radgrdResultDetail.MasterTableView.Columns)
            {
                item["run_Date"].BackColor = Color.FromArgb(255, 106, 106);

            }
        }

however its trying to access the "Date" - that i'm coming across my error i've attached an image of my e.item

enter image description here

Upvotes: 0

Views: 1286

Answers (2)

Niranjan Singh
Niranjan Singh

Reputation: 18290

Try this

protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    //Is it a GridDataItem
    if (e.Item is GridDataItem)
    {
        //Get the instance of the right type
        GridDataItem item= e.Item as GridDataItem;

        //Check the formatting condition
        if(DateTime.Compare(Convert.ToDateTime(item["run_date"].Text), DateTime.Now) > 0)
        {
            item["run_Date"].BackColor = Color.FromArgb(255, 106, 106);
            //Customize more...
        }
    }
}

Ref:
Conditional formatting for rows/cells on ItemDataBound
How to change row color for RadGrid with specified conditions?

Upvotes: 1

Matt
Matt

Reputation: 126

What's the exact error message you are receiving? My assumption is that you are getting an invalid cast exception as you are comparing a String cell.Text to a DateTime object DateTime.Now. Try converting the text to a datetime object like this:

if(DateTime.Compare(Convert.ToDateTime(item["run_date"].Text), DateTime.Now) > 0)

or look at the cell itself, which I think returns an object, and cast it to a datetime object

if(DateTime.Compare((DateTime)item["run_date"], DateTime.Now) > 0)

Upvotes: 1

Related Questions