views:

380

answers:

2

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?

+1  A: 

The problem is that the up/down control automatically increments or decrements the currently highlighted portion of the date/time picker (i.e. year/month/day/hour/etc.).

You are probably better off adding your own up/down control (perhaps a very small vscrollbar) immediately adjacent to the date/time picker and wiring it up to increment/decrement five minute intervals from the date/time picker's value.

kronoz
+1  A: 

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;
    }
}
Hans Passant