user2137186
user2137186

Reputation: 837

DateTimePicker Change Value on Click In windows Form Application C#

I Am using a DateTime Picker in WindowsForm Application of C#. I initalize My dateTImePicker with DateTime.Min Value. What I want is that when a user clicks that dropdown It Should Change its value to DateTime.Now Value and show the current value in calendar but I have to first open it then close it and then reopen it to get the required date in calendar. How can I Do it in a single Click? Any Help will be appreciated.

So far I have tried these events:

private void GroupEndingDate_MouseUp(object sender, MouseEventArgs e)
        {
            GroupEndingDate.Value = DateTime.Now;
        }

        private void GroupStartingDate_MouseDown(object sender, MouseEventArgs e)
        {
            GroupStartingDate.Value = DateTime.Now;
        }

        private void GroupStartingDate_DropDown(object sender, EventArgs e)
        {
            GroupStartingDate.Value = DateTime.Now;
        }

Upvotes: 2

Views: 4546

Answers (2)

Jonathan Wood
Jonathan Wood

Reputation: 67355

The following works just fine for me without having to click the control a second time.

private void dateTimePicker1_DropDown(object sender, EventArgs e)
{
    dateTimePicker1.Value = DateTime.Now;
}

But I agree this approach seems a little odd to me. The date will be set every time the control opens up. Why not just initialize it to DateTime.Now in your form's Load event?

Upvotes: 0

misfitgeek
misfitgeek

Reputation: 105

Try this in your dropdown event. This worked for me.

private void Form1_Load(object sender, EventArgs e)
{
    dateTimePicker1.Value = DateTime.Now.AddDays(-3);
}

private void dateTimePicker1_DropDown(object sender, EventArgs e)
{
    dateTimePicker1.Value = DateTime.Now;
}

Upvotes: 2

Related Questions