Search code examples
asp.netgridviewcellsystem.drawingrowdatabound

I am trying to show background red for expiring items in my gridview but not able to using asp.net


I have a gridview that I am binding on my page_load event. In that, is a expiry date column where I want t show in red colour for those which are expiring in and under 30 days. Below is my GridView1_RowDataBound event code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    string ddmmyyyy = DateTime.Now.ToString("dd-MM-yyyy");
    DateTime nowDate = Convert.ToDateTime(ddmmyyyy);//DateTime.ParseExact(ddmmyyyy, "dd-MM-yyyy", null);
    DateTime TableDate = Convert.ToDateTime(e.Row.Cells[6].Text);
    if (e.Row.RowIndex >= 0)
    {
        if (TableDate <= nowDate.AddDays(-30))
        {
            e.Row.Cells[6].BackColor = Color.Red;
        }
    }
}

and here is the screenshot of the gridview. Image It's throwing an exception saying that the date time format is invalid. Kindly help me solve this.


Solution

  • First thing, your gridview RowDataBound code should be within following condition. Than try following code:

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string date = "30-05-2018"; //Cell value
        DateTime getdate = Convert.ToDateTime(date, System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
        DateTime CurrentDate = Convert.ToDateTime(DateTime.Now, System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
    
        if ((CurrentDate - getdate).TotalDays < 30)
        {
           e.Row.Cells[6].BackColor = System.Drawing.Color.Red;
        }
    }