I'm letting users select a date/time for a scheduled task to run, using two NumericUpDown
controls.
I'd like one-digit values to be padded with a leading 0, so as to display 09:00
instead of 9:0
.
The definitive solution is to use a DateTimePicker
with 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.
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.
This is not possible with a NumericUpDown Control.
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
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;
}
}
}