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

264 Views Asked by At

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.

2

There are 2 best solutions below

0
Gaurav On BEST ANSWER

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;
    }
}  
1
Ravikumar On

Try following code.

GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int value = (int)DataBinder.Eval(e.Row.DataItem, e.Row.Cells[2].Text); 
        // e.Row.Cells[2] references the cell value you want to use
        if (value < 100)
        {
            e.Row.Cells[2].BackColor = Color.FromName("#c6efce");
        }
        if ((value >= 100) && (value < 500))
        {
            e.Row.Cells[2].BackColor = Color.FromName("#ffeb9c");
        }
        if (value >= 500)
        {
            e.Row.Cells[2].BackColor = Color.FromName("#ffc7ce");
        }
    }
}