您使用OnRowDataBound
事件。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
DateTime _currentDate = new DateTime();
DateTime _dueDate = new DateTime();
//first, check if the date fields are null or empty and then try to convert
if (!string.IsNullOrEmpty(row["currentDate"].ToString()))
{
_currentDate = Convert.ToDateTime(row["currentDate"]);
}
if (!string.IsNullOrEmpty(row["dueDate"].ToString()))
{
_dueDate = Convert.ToDateTime(row["dueDate"]);
}
//check the value of progress and set the background color
if (Convert.ToInt32(row["progress"]) < 100 && _currentDate > _dueDate)
{
e.Row.Cells[0].BackColor = Color.Red;
}
}
}
您需要將OnRowDataBound="GridView1_RowDataBound"
添加到GridView。
如果您綁定的List<Myclass>
你做這個類的列表:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if you bound a list of classes to the GridView, cast back to the orignal class
MyClass item = e.Row.DataItem as MyClass;
//check the propertyu value of the class and set the background color
if (item.progress < 100 && item.currentDate > item.dueDate)
{
e.Row.Cells[0].BackColor = Color.Red;
}
}
}
,如果我想添加'和'有條件的話就用想如果'(Convert.ToInt32(行[「進步」]) <100 && row [「stardate」]> row [「duedate」])'或者我錯了? – Pepe
是的,但你需要轉換爲DateTime'Convert.ToDateTime(row [「duedate」])' – VDWWD
你能檢查我的編輯你的答案嗎?如果我只是使用「進度」驗證它的工作原理:'if(progress <100)',但如果我添加Date驗證像'(progress <100 && currentDate> dueDate)'它會拋出錯誤 – Pepe