zoukankan      html  css  js  c++  java
  • 限制TextBox输入,只能输入整数

     1     public class TextBoxInt : TextBox
     2     {
     3         public TextBoxInt()
     4         {
     5             KeyDown += TextBoxInt_KeyDown;
     6             TextChanged += TextBoxInt_TextChanged;
     7         }
     8 
     9         private void TextBoxInt_TextChanged(object sender, TextChangedEventArgs e)
    10         {
    11             //屏蔽非法字符粘贴
    12             var textBox = sender as TextBox;
    13             if (textBox != null)
    14             {
    15                 var change = new TextChange[e.Changes.Count];
    16                 e.Changes.CopyTo(change, 0);
    17 
    18                 int offset = change[0].Offset;
    19                 if (change[0].AddedLength > 0)
    20                 {
    21                     int num;
    22                     if (!int.TryParse(textBox.Text, out num))
    23                     {
    24                         textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
    25                         textBox.Select(offset, 0);
    26                     }
    27                 }
    28             }
    29         }
    30 
    31         private void TextBoxInt_KeyDown(object sender, KeyEventArgs e)
    32         {
    33             if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
    34             {
    35                 // 允许输入数字小键盘上的数字0-9
    36                 e.Handled = false;
    37             }
    38             else if ((e.Key >= Key.D0 && e.Key <= Key.D9) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
    39             {
    40                 // 允许输入数字0-9,并且不能同时按着Shift键
    41                 e.Handled = false;
    42             }
    43             else if (e.Key == Key.Enter)
    44             {
    45                 // 允许输入回车
    46                 e.Handled = false;
    47             }
    48             else
    49             {
    50                 e.Handled = true;
    51             }
    52         }
    53     }
  • 相关阅读:
    sqlserver 跟踪标志
    解决ORA-00338,ORA-00312
    oracle SQL性能分析
    高潜力人士和员工
    pymysqlreplication
    Python3操作Excel(写入)
    CentOS7.4 源码安装MySQL8.0
    MySql 时间操作实例
    python+eclipse+pydev开发环境搭建
    MySQL表结构同步工具 mysql-schema-sync
  • 原文地址:https://www.cnblogs.com/candyzkn/p/3455641.html
Copyright © 2011-2022 走看看