0

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
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
software is fun
  • 7,286
  • 18
  • 71
  • 129
  • I answered one question. You should ask one question per, uh, question. – David Crowell Sep 16 '14 at 17:02
  • 1
    Please read the [documentation](http://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx) next time. One of the very first examples for `DateTime` shows that `new DateTime()` defaults to `1/1/0001 12:00:00 AM.` Or even just using your debugger. Wouldn't take much effort to notice that the `DateTime` object you're creating isn't today's date. – tnw Sep 16 '14 at 17:06
  • Not to be mean, but [your code smells](http://c2.com/cgi/wiki?SwitchStatementsSmell). You should probably try using LINQ, [rather than **if**](http://stackoverflow.com/questions/1554180/why-is-the-if-statement-considered-evil). – Scott Solmer Sep 16 '14 at 17:14

1 Answers1

6

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;

David Crowell
  • 3,711
  • 21
  • 28