Search code examples
c#copy-pastedatetimepicker

Pasting values into DatetimePicker


I have DateTimePicker controls in my C# Windows application. Some of them are formatted to show date while others show time.

A user wants to click on some textbox field which contains time in text format like 14:25:56 and press CTRL + C. Then he would like to click on the DateTimePicker and press CTRL + V to paste this time into date in DateTimePicker.

It doesn't work by default. Is it possible to make something like it working at all?


Solution

  • I did something similar about a year ago with pasting values into a data grid. I handled it by putting an event handler on the KeyDown event of the control that you want to paste the value into, then you can use the event args to check which of the characters (in this case, V) is pressed and which modifier keys (CTRL, SHIFT, ALT, etc.) are pressed.

    Once you know CTRL+V was pressed, you can create some code to parse through the string returned by Clipboard.GetText(); using DateTime.Parse(); as defined on MSDN and store the value in the date-time picker. Here is what I got. You will want to do some validation to make sure the text is in the right format. You can do this with DateTime.TryParse(); instead of DateTime.Parse() like I am using.

    private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V)
        {
            dateTimePicker1.Value = DateTime.Parse(Clipboard.GetText());
            e.Handled = true;
        }
    }
    

    I hope this helps.