How to use a date-time picker control in WinForm?
To use a DateTimePicker control in WinForms, you first need to add a DateTimePicker control to the form in Visual Studio. You can do this by dragging and dropping the DateTimePicker control from the toolbox onto the form, or by dynamically adding the control in the code.
You can set some properties of the DateTimePicker control, such as the minimum date, maximum date, and date format, when the form is loaded. Then you can use the Value property of the DateTimePicker control to retrieve or set the selected date and time value.
Here is a simple example code demonstrating how to use the DateTimePicker control in WinForm.
using System;
using System.Windows.Forms;
namespace DateTimePickerExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 设置日期时间选择器的格式为日期和时间
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy-MM-dd HH:mm:ss";
// 设置日期时间选择器的最小日期和最大日期
dateTimePicker1.MinDate = new DateTime(2021, 1, 1);
dateTimePicker1.MaxDate = new DateTime(2022, 12, 31);
}
private void button1_Click(object sender, EventArgs e)
{
// 获取选择的日期时间值
DateTime selectedDate = dateTimePicker1.Value;
MessageBox.Show("选择的日期时间是:" + selectedDate.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
}
In the example above, we created a form, added a DateTimePicker control, and a button. We set the date and time format as well as the minimum and maximum dates for the DateTimePicker control when the form loads. When the user clicks the button, we retrieve the selected date and time value using the Value property, and display it in a MessageBox.