Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...