为什么我会崩溃并在一周中错误的一天?

时间:2014-09-16 17:00:06

标签: c# datagridview switch-statement datagridviewrow

我的系统时钟是9/16/2014(星期二)

但是在代码中,我总是跳到星期一。

DayOfWeek dow = new DateTime().DayOfWeek;
int columnNumber = 0;

columnNumber = columnNumber + 0;

foreach ( DataGridViewRow row in dataGridView1.Rows )
{
  switch ( dow )
  {
  case DayOfWeek.Monday:
    columnNumber = 4;
    if ( (bool) row.Cells[4].Value == true ) // crashing here with NullReferenceException
    {
      row.Cells["activeTodayDataGridViewCheckBoxColumn"].Value = true;
    }
    break;

我有DataGridView

  • 第0-3列是Text
  • 第4-9列是DataGridViewCheckBoxColumn

1 个答案:

答案 0 :(得分:6)

new DateTime()未提供今天的日期,但DateTime的默认值

您想将该行更改为:

DayOfWeek dow = DateTime.Now.DayOfWeek;