VS C# DateTimePicker()的小技巧

今天要改个东西,说是要改个C/S的日期时间框的默认值,查了下MSDN,使用DATETIMEPICKER的format属相和
customformat属性来实现.
最开始自己写了个测试的代码段:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Globalization;

namespace TimePickerApplication
{
    public class Form1 : Form
    {
        public Form1()
        {
            InitializeTimePicker();
        }

        private DateTimePicker dtpFrom;
        private DateTimePicker dtpTo;

        private void InitializeTimePicker()
        {
            dtpFrom = new DateTimePicker();
            dtpTo = new DateTimePicker();

            dtpFrom.Format = DateTimePickerFormat.Custom;
            dtpFrom.CustomFormat = "MM/dd/yyyy HH:mm";
            dtpFrom.Value= DateTime.ParseExact("00:01", "HH:mm",null);

            dtpTo.Format = DateTimePickerFormat.Custom;
            dtpTo.CustomFormat = "MM/dd/yyyy HH:mm";
            dtpTo.Value= DateTime.ParseExact("23:59", "HH:mm",null);

            dtpFrom.Location = new Point(10, 10);
            dtpTo.Location = new Point(10, 50);

            dtpFrom.Width = 130;
            dtpTo.Width = 130;
            Controls.Add(dtpFrom);
            Controls.Add(dtpTo);
        }

        [STAThread]

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

    }
}

这样写好以后,效果如下

这样是出来了,日期可以用下拉菜单去改,但是时间不能自己控制.于是想到了用DateTimePicker.Value.Hour, Minute,不过刚回过神,这2个不都是Readonly的嘛 = =!NND.那怎么办呢...

于是乎想到了用DateTime.ParseExact()来实现value的默认值.然后再事件里触发再去记录最后改动的值,事件触发就不写了,很简单很容易,主要是这个DateTime.ParseExact(),后来加入了红色的代码段,OK.
最后效果图如下:

如果想详细看看这个
DateTime.ParseExact()请参考这里:
System.DateTime.ParseExact()

DateTimePicker的相关信息请参考这里:
System.Windows.Forms.DateTimePicker()

日期时间字符串格式参考这里
Date and Time Format Strings



posted @ 2008-05-13 15:27  荖K  阅读(11663)  评论(0编辑  收藏  举报