程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 時間格式的TextBox控件代碼

C# 時間格式的TextBox控件代碼

編輯:C#入門知識

作者:肖肖 源代碼: 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;//獲取光標位置
            if (e.KeyChar >= 48 && e.KeyChar <= 57)//判斷所輸入的是數字還是其他字符
            {
                if (index>=0 && index<5)//判斷光標位置
                {
                    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);
            }
        }
 //判斷輸入的時間是否為24小時制
        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);
        

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved