0

所以经常,我希望用户选择开始日期和结束日期。但仅选择日期是不够的,我们还必须更改数据。

默认情况下,DateTimePicker.Value就像

Value 1: 2012-01-01 10:12:09
Value 2: 2012-01-02 10:12:09

当用户选择两个日期时,很明显他的意思是

Value 1: 2012-01-01 00:00:00
Value 2: 2012-01-02 23:59:59

我经常忘记做不直观的事情

DateTime start = dateTimePicker1.Value.Date;
DateTime finish = dateTimePicker2.Value.Date.AddDays(1).AddSeconds(-1);

您找到了哪些更有效的处理方法?

4

1 回答 1

1

如果你经常使用DateTimePicker像这样的对象,你可以创建两个小的自定义类:aStartDateTimePicker和 an EndDateTimePicker。每个类都将派生自DateTimePicker,并且仅在OnValueChanged事件上有一个布尔值和一个 EventHandler。该事件将用于在设置后调整值,而布尔值将用于实现Balking Pattern。这是一个示例StartDateTimePicker

public class StartDateTimePicker : DateTimePicker
{
    bool handling = false;

    // Note: 
    public StartDateTimePicker()
        : base()
    {
        // This could be simplified to a lambda expression
        this.ValueChanged += new EventHandler(StartDateTimePicker_ValueChanged);
    }

    void StartDateTimePicker_ValueChanged(object sender, EventArgs e)
    {
        // If the value is being changed by this event, don't change it again
        if (handling)
        {
            return;
        }
        try
        {
            handling = true;
            // Add your DateTime adjustment logic here:
            Value = Value.Date;
        }
        finally
        {
            handling = false;
        }
    }
}

然后,您只需使用这些来代替您的普通DateTimePicker对象,您就不必再担心确保日期被适当地调整了。

It would cost you the time to write the EndDateTimePicker class (the above is already a fully functional StartDateTimePicker), but it would make things easier down the road as you use these in more places.

于 2012-06-29T12:53:53.977 回答