C#datagridview比较每一行的单元格值

时间:2015-01-07 20:32:55

标签: c# winforms datagridview

尽可能清楚地解释这一点。

我有一个datagridview。我有3行和7个单元格。在第7个单元格上存储了DateTimePicker值。我想比较每行的第7个单元格的值和某个日期。如果第7个单元格的日期值高于我想要比较的日期值,请将该行用红色着色。

我走了这么远:

foreach(DataGridViewRow r in dataGridView1.Rows)
{
  if( dont know what to type here) 
      {
         r.DefaultCellStyle.BackColor = Color.Red; 
        }
}

3 个答案:

答案 0 :(得分:1)

你需要提取第7个单元格Value并将其转换/转换为DateTime然后你可以比较它:(记住单元格是基于0的,所以第7个单元格将位于r.Cells[6]

DateTime yourCompareDate = DateTime.Now;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
    DateTime cellValue7 = Convert.ToDateTime(r.Cells[6].Value); //Convert/Cast value to date
    if(cellValue7 > yourCompareDate)
    {
        r.DefaultCellStyle.BackColor = Color.Red;
    }
}

答案 1 :(得分:0)

试试这个:

var compareDate = DateTime.Now; //or whatever date you want
foreach(DataGridViewRow r in dataGridView1.Rows)
    {
      var cellDate = Convert.TodateTime(r.Cells[6].Value); 
      if (cellDate > compareDate) r.DefaultCellStyle.BackColor = Color.Red;    
     }

答案 2 :(得分:0)

        DateTime dtValue = DateTime.Now;  // You Date Time Value
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            if ((DateTime)r.Cells[6].Value > dtValue)
            {
                r.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
            }
        }