我的代码适用于更改行中的颜色,但我需要使用正确的if语句。在单元格[0]中,我有日期值" 2013.03.20"。此日期表示产品已过期。
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0](dont know how write))
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
示例:
答案 0 :(得分:4)
像这样的事情(我的头顶没有Visual Studio所以请原谅任何轻微的语法错误)。使用DateTime转换处理空值,无效日期等可能需要更加健壮。您可以调整条件以符合您的确切要求:
foreach (DataGridViewRow row in dataGridView1.Rows)
switch (Convert.ToDatetime(row.Cells[0].ToString()))
{
case > DateTime.Today:
row.DefaultCellStyle.BackColor = SomeColor;
break;
case == DateTime.Today:
row.DefaultCellStyle.BackColor = SomeColor;
break;
case else:
row.DefaultCellStyle.BackColor = SomeColor;
break;
}
答案 1 :(得分:3)
正如西蒙所说,你也应该为DateTime处理错误的日期格式。
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var now = DateTime.Now;
var expirationDate = DateTime.Parse(row.Cells[0].Value.ToString());
var sevenDayBefore = expirationDate.AddDays(-7);
if (now > sevenDayBefore && now < expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else if (now > expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
答案 2 :(得分:0)
您可以使用 RowDataBound 事件处理程序,而不是使用foreach。我认为使用RowDataBound事件处理程序是为了那些事情。
public void dataGridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Product currentProduct = e.Item.DataItem as Product;
TimeSpan diffDate = DateTime.Now - currentProduct.ExpireDate;
if (dateDiff < TimeSpan.FromDays(0))
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else if (dateDiff < TimeSpan.FromDays(7))
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
}
答案 3 :(得分:0)
试试这个例子。
DateTime currentToday = (DateTime)this.dataGridView1.Rows[e.RowIndex].Cells["Date"].Value;
if (currentToday <= DateTime.Now.Date)
{
e.CellStyle.ForeColor = Color.Red; //Font Color
e.CellStyle.SelectionForeColor = Color.Red; //Selection Font color
}