C#日历控件DateTimePicker 使用详解

2022-07-25,,,

DateTimePicker控件(日期控件)
DateTimePicker控件(日期控件)用于选择日期和时间,但只能选择一个时间,而不是连续的时间段,也可以直接输入日期和时间。
1.使Date用 Time Picker控件显示时间
通过将控件的 Format属性设置为Time,实现控件只显示时间。 Format属性用于获取或设置控件中显示的日期和时间格式。
语法如下:

 public DateTimePickerFormat Format {get; set;}

属性值: DateTimePickerFormat值之一,默认为Long
DateTime PickerFormat枚举的值及说明如下表

如下例子

using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Test14
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd";
            label1.Text = dateTimePicker1.Text;
        }
    }
}

结果如图

2.使用 DateTimePicker控件以自定义格式显示日期
通过 DateTime Picker控件的 CustomFormat属性可以自定义日期/时间格式字符串。
语法如下:

public string CustomFormat {get; set;}

属性值:表示自定义日期/时间格式的字符串。
通过组合格式字符串,可以设置日期时间格式,所有的有效格式字符串及其说明如下表所示。

3.返回 DateTimePicker控件中选择的日期
调用控件的Text属性以返回与控件中的格式相同的完整值,或调用 Value属性的适当方法来返回部分值,这些方法包括Year、 Month和Day方法等。使用 ToString将信息转换成可显示给用户的字符串。
如下例子

using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Test15
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = dateTimePicker1.Text;
            textBox2.Text = dateTimePicker1.Value.Year.ToString();
            textBox3.Text = dateTimePicker1.Value.Month.ToString();
            textBox4.Text = dateTimePicker1.Value.Day.ToString();
        }
    }
}

结果如下

本文地址:https://blog.csdn.net/weixin_54025128/article/details/112688269

《C#日历控件DateTimePicker 使用详解.doc》

下载本文的Word格式文档,以方便收藏与打印。