formating 24hour time as enterd by the programs user
I have a question in relation to formatting text fro 24-hour time.
The format I开发者_高级运维 require is always as follows 00:00
How can I make the “:” appear as soon as the second digit is entered as this is required to separate hours from minutes and also how can I force a 0 to appear for any numbers up to and including 9?
Examples being: 00, 01, 02, 03, 04, 05, 06, 07, 08, 09.
These zeros are required but may be forgotten by the user entering them into the textbox?
Use a MaskedTextBox. You can set the .Mask
property to "00:00"
, and the box will look like _ _ : _ _
while the user is inputting the time (so it won't appear after the second digit, but it will always be there as a guide).
To verify that the hours are within 0-23 and the minutes from 0-59, use the Validating
method (see [this MSDN post] for the details).
if you want the : too, use this veersion. Add the 0 if the user types any number > 3 (0, 1 and 2 might be a 2-digit hour)
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
If TextBox1.Text.Length() = 2 Then
TextBox1.Text &= ":"
TextBox1.SelectionStart = TextBox1.Text.Length()
End If
If TextBox1.Text.Length() = 1 AndAlso TextBox1.Text > "2" Then
TextBox1.Text = "0" & TextBox1.Text
TextBox1.SelectionStart = TextBox1.Text.Length()
End If
End Sub
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = vbBack AndAlso TextBox1.Text.Length() = 3 Then
TextBox1.Text = TextBox1.Text(0)
e.Handled = True
End If
End Sub
精彩评论