8

I'm letting users select a date/time for a scheduled task to run, using two NumericUpDowncontrols.

I'd like one-digit values to be padded with a leading 0, so as to display 09:00 instead of 9:0.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Clément
  • 12,299
  • 15
  • 75
  • 115

5 Answers5

7

The definitive solution is to use a DateTimePickerwith ShowUpDown set to True and Format set to Time or Custom. In the latter case, you'd use hh:mm or HH:mm as a custom format.

Clément
  • 12,299
  • 15
  • 75
  • 115
5
class CustomNumericUpDown:System.Windows.Forms.NumericUpDown
{
    protected override void OnTextBoxTextChanged(object source, EventArgs e)
    {
        TextBox tb = source as TextBox;
        int val = 0;
        if (int.TryParse(tb.Text,out val))
        {
            if (val < 10)
            {
                tb.Text = "0" + val.ToString();
            }
        }
        else
        {
            base.OnTextBoxTextChanged(source, e);
        }
    }
}

I had to do this this morning and came up with a Customised Numeric Up Down for my Windows Forms application. You should be able to change this easily enough to VB.NET.

LeeSalter
  • 51
  • 1
  • 2
2

This is not possible with a NumericUpDown Control.

0x90
  • 293
  • 2
  • 9
2

I have a clever idea~ Why don't you put a textbox covering the textbox part of the numericupdown control (only the scroll of numericupdown will be shown)?

Set your textbox with "00" as the initial value, then disable it, so that the user can't control your textbox.

Then type these codes:

Private Sub numericupdown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ndFrom.ValueChanged

        If numericupdown1.Value < 10 Then
            textbox1.Text = "0" & numericupdown1.Value
        Else
            textbox1.Text = numericupdown1.Value
        End If


End Sub
ajtrichards
  • 29,723
  • 13
  • 94
  • 101
mitoshi
  • 21
  • 1
  • 1
    Yup, but this is a bit hackish, not very clean. I guess you would most likely use a label though, not a textbox. – Clément Feb 17 '11 at 10:44
-1
class MyNumericUpDown : System.Windows.Forms.NumericUpDown
{
   public override string Text
   {
      get
      {
         return base.Text;
      }
      set
      {
         if (value.Length < 2)
            value = "0" + value;

         base.Text = value;
      }
   }
}