Monday, June 9, 2014

C# DateTimePicker and Current Time a.k.a Learning to Load

This is a "helpful hint" post. I was working on a Windows Form and needed the form to update to the current time each time the app was run. I started with the TimeDatePicker in the form, choosing Time for the property Format because I only wanted to display the time, not the date. I didn't have to set Value because that property was automatically set to the current date and time. The code I used was:
private void DateTimePicker_Click(object send, EventArgs e) 
{ DateTime.dateTimePicker1 = DateTime.Now;}
Unfortunately, this combo did not work. Each time I ran the app, it showed the time the app was created and not the current time.

The first lesson here is to not assume that Click is an event for every controller. It's not an event for DateTimePicker. It seemed logical to me, though, so I used that in my code without checking to see if it was an actual event. You click to change the date and/or time, right? Yes, you do. But that was the wrong logic.

The correct logic is to ask: A) What should the controller do? The controller should show the current time. B) When should the controller perform this task? The controller should perform this task when the form loads, which means the data needs to be picked up before the form displays.

Here is one way to write the code correctly:
private void Form1_Load(object sender, EventArgs e)
      {     //Form1 is the name of the class used to create this form
         dateTimePicker1.Value = DateTime.Now;
      }//also see DotNetPerls for another snippet

Since my textbook didn't go into a lot (i.e., any) detail about loading, I had to do a little research. Although I ran across references to Load when I was searching high and low for a way to make the time update, I couldn't find it as an event for DateTimePicker. That's because Load is an event of class Form, which is a class in the Forms namespace. (When you create a form, you will see that the class automatically generated for you is a derived class of class Form.) In the order of events, Load occurs before the form is displayed, which is logical.

The moral of the story is that if you want the current date, i.e. data that must be captured anew each time the app is run, you need the Load event. Just remember that Load is an event of class Form, not the controller DateTimePicker,

I strongly recommend reading these two posts by DotNetPerls: One on Load and one on DateTimePicker to help you understand this better.

No comments:

Post a Comment