Manali
Manali

Reputation: 315

key_down event of DateTimePicker

I am using this DateTimePicker control in my UI.

I want my control to behave like when user presses 'delete' or 'backspace' key the value displayed on DateTimePicker control should be an empty string.

Intially I managed by setting its CustomFormat property to empty string so that when UI loads it shows as null.

I am using KeyDown event to check/verify if user has enterd Delete or Backspace key. Kindly help.

Manali

Upvotes: 2

Views: 4203

Answers (2)

christoph
christoph

Reputation: 126

This should work for you. You need to reset the format back to your desired format (Long, Short, Time, Custom), before you can get a new value. Do this in the ValueChanged event.

    private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back)
        {
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = " ";
        }
    }

    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
        dateTimePicker1.Format = DateTimePickerFormat.Long;
    } 

When saving a value for the dateTimePicker, you can test if the dateTimePicker1.Format == DateTimePickerFormat.Custom, and then save the value as null in your database.

Enjoy!

Upvotes: 2

Haris Hasan
Haris Hasan

Reputation: 30097

  private void date_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Back || e.Key == Key.Delete)
                date.SelectedDate = null;
        }

Upvotes: 2

Related Questions