为以编程方式创建的DateTimePicker创建事件

时间:2018-02-27 15:03:45

标签: c# winforms datetimepicker

我以编程方式创建了一个DateTimePicker:

Controls.Add(new DateTimePicker { Name = "txtPaymentDate", 
                                  Location = new Point(146, 232),
                                  Size = new Size(113, 20),
                                  Format = DateTimePickerFormat.Custom,
                                  CustomFormat = " ", TabStop = false });

如果DateTimePicker未打开,则不会有默认日期。但是每当我使用 CloseUp Event 选择日期时,我想更改DateTime格式。但是,由于DateTimePicker是手动创建的,我不知道如何为它创建事件。

如何为它创建活动?

1 个答案:

答案 0 :(得分:3)

你可以这样做

DateTimePicker myPicker = new DateTimePicker { Name = "txtPaymentDate", 
                                               Location = new Point(146, 232), 
                                               Size = new Size(113, 20), 
                                               Format = DateTimePickerFormat.Custom, 
                                               CustomFormat = " ", 
                                               TabStop = false };
myPicker.CloseUp += myPicker_CloseUp;

Controls.Add(myPicker);

private void myPicker_CloseUp(object sender, EventArgs e)
{
    if (sender is DateTimePicker)
    {
       ((DateTimePicker)sender).Format = 'dd-MM-yyyy'; 
    }
}

如果您希望事件只针对特定的DateTimePicker(按名称)执行操作,则可以执行此操作:

private void myPicker_CloseUp(object sender, EventArgs e)
{
    if (sender is DateTimePicker)
    {
       if (DateTimePicker)sender).Name == "txtPaymentDate")
           ((DateTimePicker)sender).Format = 'dd-MM-yyyy'; 
    }
}