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 formdateTimePicker1.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