C # TextBox Control Code in time format

Source: Internet
Author: User

Author: Xiao source code: using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Drawing;
Using System. Data;
Using System. Text;
Using System. Windows. Forms; namespace TimeTextBoxControl
{
Public partial class TimeTextBoxControl: UserControl
{
Public TimeTextBoxControl ()
{
InitializeComponent ();
If (textBox1.Text. Equals (""))
{
TextBox1.Text = "00:00 ";
}
} Public string TimeText
{
Get {return textBox1.Text ;}
Set {textBox1.Text = value ;}
} Private void textBox1_KeyPress (object sender, KeyPressEventArgs e)
{
TimeFormat (sender, e );
String currStr1 = "";
String currstr2 = "";
Int index = textBox1.SelectionStart; // obtain the cursor position
If (e. KeyChar> = 48 & e. KeyChar <= 57) // you can specify whether the input is a number or another character.
{
If (index> = 0 & index <5) // you can specify the cursor position.
{
If (textBox1.SelectionStart = 2)
{
CurrStr1 = textBox1.Text. Substring (0, index) + ":";
Currstr2 = textBox1.Text. Substring (index + 2 );
Index ++;
}
Else
{
CurrStr1 = textBox1.Text. Substring (0, index );
Currstr2 = textBox1.Text. Substring (index + 1 );
}
TextBox1.Text = currStr1 + e. KeyChar. ToString () + currstr2;
}
TextBox1.SelectionStart = index + 1;
}
Else
{
E. KeyChar = Convert. ToChar (0 );
}
If (textBox1.Text. Length> = 5)
{
E. KeyChar = Convert. ToChar (0 );
}
}
// Determine whether the input time is in the 24-hour format
Private void timeFormat (object sender, KeyPressEventArgs e)
{
If (textBox1.SelectionStart = 0)
{
If (e. KeyChar <48 | e. KeyChar> 50)
{
E. KeyChar = Convert. ToChar (48 );
}
}
If (textBox1.SelectionStart = 1)
{
If (textBox1.Text. Substring (0, 1). Equals ("0 ")))
{
If (e. KeyChar <48 | e. KeyChar> 57)
{
E. KeyChar = Convert. ToChar (0 );
}
}
Else
{
If (e. KeyChar <48 | e. KeyChar> 52)
{
E. KeyChar = Convert. ToChar (0 );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.