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

Create an event for a DateTimePicker that was created programmatically

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

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

如果 DateTimePicker 未打开,它将没有默认日期。但是我想在我 select 使用 CloseUp 事件 的日期时更改 DateTime 格式。但是,由于 DateTimePicker 是手动创建的,我不知道如何为其创建事件。

如何为其创建活动?

你可以这样做

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'; 
    }
}