Reputation: 15
My code works for changing color in rows, but I need to make correct if statement. In cell[0] I have date value "2013.03.20". This date means product expired date.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0](dont know how write))
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
Example:
Upvotes: 0
Views: 9209
Reputation: 174
You can use RowDataBound event handler instead of using foreach. I think using RowDataBound event handler is for those things.
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;
}
}
}
Upvotes: 0
Reputation: 2458
Try this example.
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
}
Upvotes: 0
Reputation: 81
As Simon said you should also handle incorrect date format for 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;
}
}
Upvotes: 3
Reputation: 6152
Something like this (off the top of my head with no Visual Studio so forgive any minor syntax errors). You would probably need to be a bit more robust with the DateTime conversion to handle nulls, invalid dates etc. You can tweak the conditions to match your exact requirements:
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;
}
Upvotes: 4