如何验证文本框的小时和分钟

时间:2014-08-21 15:01:04

标签: silverlight c#-4.0 silverlight-4.0

使用C#,visualstudio 2010,silverlight 2个文本框,1个名称为

的名称

textbox1,textbox2,button1

textbox1 - input allow only hours (HH)
textbox2 - input allow only minutes (mm)

button1_click事件

我想验证带有以下条件的textbox1,textbox2

textbox1, allow only hours between 00 to 23
textbox2, allow only minutes between 00 to 59

如何编写代码或函数。需要代码帮助

1 个答案:

答案 0 :(得分:0)

我认为这是你正在努力实现的目标

  1. 将文本框的最大长度设置为2
  2. 将两个文本框的keydown连接到commonhandler并阻止非数字键按
  3. 在按钮上单击以验证小时和分钟的范围。以下是样本。
  4.   

    public partial class MainPage:UserControl       {           公共MainPage()           {               的InitializeComponent();               txHour.MaxLength = 2;               txtMinutes.MaxLength = 2;               txHour.KeyDown + = new KeyEventHandler(txt_KeyDown);               txtMinutes.KeyDown + = new KeyEventHandler(txt_KeyDown);

        }
        private void txt_KeyDown(object sender, KeyEventArgs e)
        {
    
            if (e.Key < Key.D0 || e.Key > Key.D9)
            {
                if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
                {
                    if (e.Key != Key.Back && e.Key != Key.Shift && e.Key != Key.Tab)
                    {
                        e.Handled = true;
                    }
                }
            }
    
        }
    
    
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            bool isvalid = false;
            int x, y;
    
            if (int.TryParse(txHour.Text, out x) && int.TryParse(txtMinutes.Text, out y))
            {
    
                if (x >= 0 && x <= 23 && y >= 0 && y <= 59)
                {
                    isvalid = true;
                }
            }
    
            if (!isvalid)
            {
                MessageBox.Show("InValidTime");
            }
    
    
        }
    
    }
    
    1. 但是如果你想限制Ctr + V(粘贴),那么你可能需要创建一个继承文本框的新文本框来解决这个问题。