Bestter
Bestter

Reputation: 878

TimeSpan picker in DataGridView that allow more than 24 hours

I need a way to create a TimeSpan time picker column, that allow more than 24 hours. Right now, I got a TimePicker which derived from the DateTimePicker, but after 24, it turn back to zero. And I didn't find a way to change it's behaviour.

Please help.

thank you!

Upvotes: 1

Views: 2492

Answers (1)

tmesser
tmesser

Reputation: 7656

Like you were thinking in the comments, probably the simplest way to handle this is to have two NumericUpDown controls - one that represents the day, and another that represents the hours.

From there, you will need to add a bit of extra logic. These spinners don't natively support 'rolling over', so you'll have to code it yourself. You add these to events, and looking through the MSDN documentation, I think you're looking at hooking on to the Click event. Nothing else looks particularly interesting.

Your code will look a little something like this:

 private void ctrlUpDownHour_Click(object sender, EventArgs e)
 {
    if(ctrlUpDownHour.Value >= 24)
    {
        ctrlUpDownDay.Value += 1;
        ctrlUpDownHour.Value -= 24;
    }
 }

Might also help if you set the ctrlUpDownHour.Maximum property to 24.

EDIT: As mentioned in the comments, probably the easiest way to handle your situation is to simply make a user control.

Simply create a new user control with two NumericUpDown controls - get started by creating a new item in your project, and clicking on the 'user control' item - this'll get you started nicely.

You can then visually design the NumericUpDown controls however you want. After that's taken care of, you can go into your code-behind, and have something that looks a little like this:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
         InitializeComponent();
         // anything else you want to do here
    }

    public TimeSpan GetSelectedTimeSpan()
    {
       return new TimeSpan((int)numericUpDown1.Value, (int)numericUpDown2.Value, 0, 0);
    }
}

You can then place this user control like any other control on any of your other forms. Then when you need the TimeSpan from it, you'll just capture the control the same as you would any other control and go userControl1Instance.GetSelectedTimeSpan().

Blammo, done.

Upvotes: 6

Related Questions