将小时DateTimePicker限制为30分钟间隔 [英] Limit hour DateTimePicker to 30 minute intervals

查看:157
本文介绍了将小时DateTimePicker限制为30分钟间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中有几个DateTimePicker控件,我需要限制用户只能从30分钟的间隔中进行选择,例如9:00-> 9:30-> 10:00-> 10:30,依此类推.这可能吗?

I have several DateTimePicker controls in C# and I need to limit the user to only choose from 30 minute intervals, e.g. 9:00 --> 9:30 --> 10:00 --> 10:30, and so on. Is this possible?

推荐答案

    public Form1()
    {
        InitializeComponent();

        if (dt.Minute % 30 > 15)
        {
            initialValue = true;
            dateTimePicker1.Value = dt.AddMinutes(dt.Minute % 30);
        }
        else
        {
            initialValue = true;
            dateTimePicker1.Value = dt.AddMinutes(-(dt.Minute % 30));
        }

        _prevDate = dateTimePicker1.Value;

    }


    private DateTime _prevDate;
    private bool initialValue = false;

    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
        if(initialValue)
        {
            initialValue = false;
            return;
        }

        DateTime dt = dateTimePicker1.Value;
        TimeSpan diff = dt - _prevDate;

        if (diff.Ticks < 0) 
            dateTimePicker1.Value = _prevDate.AddMinutes(-30);
        else 
            dateTimePicker1.Value = _prevDate.AddMinutes(30);

        _prevDate = dateTimePicker1.Value;
    }

这应该有效.您需要全局变量/属性来存储_prevDate.您可以在Form1()或Form Load中设置_prevDate.

This should work. You need global variable/Property to store _prevDate. You set the _prevDate in Form1() or on Form Load.

我们每次如何添加/删除30分钟.

How we are adding/removing 30 minutes every time.

在值更改事件中,您正在获取当前的dataPicker值,然后计算出currentValue和prevValue之间的差.如果值> 0添加,并且值< 0删除.

On value Change event you are taking the current dataPicker Value, after that you calculate the difference between currentValue and prevValue. If the value > 0 Add, and value<0 Remove.

如果您不知道如何更改DatePicker以显示分钟,则需要将此添加到设计器中.您需要以下代码:

If you don't know how to change the DatePicker to show minutes you need this to add in the designer. You need this code:

        this.dateTimePicker2.CustomFormat = "dd/MM/yyyy hh:mm";
        this.dateTimePicker2.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
        this.dateTimePicker2.ShowUpDown = true;

我添加了将在00或30上启动DataPicker的代码,具体取决于与30或00的接近程度.您需要另一个类型为bool的全局变量,该变量将把dateTimePicker的initialValue放入.查看代码.

I add the code which will start the DataPicker on 00 or 30 depending how close is to 30 or 00. You need another global variable of type bool which will put initialValue of the dateTimePicker. See the code.

这篇关于将小时DateTimePicker限制为30分钟间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆