Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to contol the time interval in a DateTimePicker

I have a DateTimePicker control on a form specified like so:

dtpEntry.Format = DateTimePickerFormat.Custom;
dtpEntry.CustomFormat = "dd/MM/yyyy hh:mm:ss";
dtpEntry.ShowUpDown = true;

I would like the user to only be able to increment or decrement the time by 5 minute increments.

Any suggestions on how one would accomplish this?

like image 808
B4ndt Avatar asked Dec 04 '09 10:12

B4ndt


1 Answers

It's possible by watching the ValueChanged event and override the value. This sample form worked well:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        dateTimePicker1.CustomFormat = "dd/MM/yyyy hh:mm";
        dateTimePicker1.Format = DateTimePickerFormat.Custom;
        dateTimePicker1.ShowUpDown = true;
        dateTimePicker1.Value = DateTime.Now.Date.AddHours(DateTime.Now.Hour);
        mPrevDate = dateTimePicker1.Value;
        dateTimePicker1.ValueChanged += new EventHandler(dateTimePicker1_ValueChanged);
    }
    private DateTime mPrevDate;
    private bool mBusy;

    private void dateTimePicker1_ValueChanged(object sender, EventArgs e) {
        if (!mBusy) {
            mBusy = true;
            DateTime dt = dateTimePicker1.Value;
            if ((dt.Minute * 60 + dt.Second) % 300 != 0) {
                TimeSpan diff = dt - mPrevDate;
                if (diff.Ticks < 0) dateTimePicker1.Value = mPrevDate.AddMinutes(-5);
                else dateTimePicker1.Value = mPrevDate.AddMinutes(5);
            }
            mBusy = false;
        }
        mPrevDate = dateTimePicker1.Value;
    }
}
like image 123
Hans Passant Avatar answered Sep 30 '22 07:09

Hans Passant