Why am I crashing and getting the wrong day of the

2019-09-06 04:18发布

问题:

My system clock is 9/16/2014 (Tuesday)

But in code, I'm always jumping to Monday.

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;

I have a DataGridView

  • Columns 0—3 are Text
  • Columns 4—9 are DataGridViewCheckBoxColumn

回答1:

new DateTime() isn't providing today's date, but the default value for DateTime

You want to change that line to :

DayOfWeek dow = DateTime.Now.DayOfWeek;