我有一个gridview,我绑定了page_load事件。在那里,是一个到期日期列,我希望在30天内到期的那些显示为红色。以下是我的GridView1_RowDataBound
事件代码:
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;
}
}
}
这是gridview的截图。
这是一个例外the date time format is invalid
。请帮我解决这个问题。
答案 0 :(得分:0)
请尝试以下代码。
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");
}
}
}
答案 1 :(得分:0)
首先,你的gridview RowDataBound代码应该在以下条件下。请尝试以下代码:
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;
}
}