When I start my program, date should be printed on label named dan.Text automatically but it prints only when I make mouse click input on GUI
This is because you only put code in the private void dan_Click(object sender, EventArgs e)
event, it will only ever work in this event.
Firstly, in your code, you have wrapped an assignment in Console.WriteLine
and it's not like you think it would. What's happening is the assignment does happen, but then the Console.WriteLine
happens which is the result of dan.Text
.
Your button text would look like:
DDDD/10/YYYY
Not what I think you'd want; it doesn't even print out a DateTime
. I think wrapping the whole thing is a type-o to be honest, just remove it. So it would look like this now:
da.Text = DateTime.Now.ToString("DDDD/MM/YYYY");
If you want to assign something to the dan.Text
property at load time, there are more than a few event's to do this as already mentioned.
One recommendation that hasn't been mentioned is overriding the OnLoad
event. This would look like:
protected override void OnLoad( EventArgs e)
{
base.OnLoad(e);
// do something here?
}
Using the event is only appropriate when another class would be interested in the event. Which is what events are for. Another class being interested in the Load event is very rare, only really useful to do window arrangement stuff.
Still, the Load event works well with the designer and programmers are very comfortable with it. It isn't horribly wrong, you'd only get in trouble when you start inheriting the form and code doesn't run in the right order.
Most code that now gets put in the Load event really belongs in the constructor.
On a final note about the DateTime.Now.ToString("DDDD/MM/YYYY")
, it's not even a valid format. To see what ones are, please see there and or here.
References:
Form_Load() 'event' or Override OnLoad()