Reputation: 377
I created a DateTimePicker programmatically like this:
Controls.Add(new DateTimePicker { Name = "txtPaymentDate",
Location = new Point(146, 232),
Size = new Size(113, 20),
Format = DateTimePickerFormat.Custom,
CustomFormat = " ", TabStop = false });
If the DateTimePicker is not open it won't have a default date. But I want to change the DateTime format whenever I select a date using the CloseUp Event. However, since the DateTimePicker was created manually I don't know how to create the event for it.
How can I create the event for it?
Upvotes: 2
Views: 1022
Reputation: 12014
You could do it like this
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';
}
}
if you want the event only do stuff for specific DateTimePicker (by name) you can do this :
private void myPicker_CloseUp(object sender, EventArgs e)
{
if (sender is DateTimePicker)
{
if (DateTimePicker)sender).Name == "txtPaymentDate")
((DateTimePicker)sender).Format = 'dd-MM-yyyy';
}
}
Upvotes: 3