zoukankan      html  css  js  c++  java
  • 创建数字文本框


     MSDN上提供了方案: 如何:创建数字文本框,它重载了TextBox类。

    当然,你也可以重写该控件而不继承任何Control类,那样在外观上效果更好。 

    MSDN上主要是做了非数字的处理,数字,逗号(可以指定),小数点,退格键和空格键是被允许输入的,当然也可以添加Ctrl和Alt组合键。当然,如果要使用还需要做进一步的处理,比如, 输入的字符串是否合理。

     以下为代码片段 

    NumericTextBox
    public class NumericTextBox : TextBox
    {
        
    bool allowSpace = false;

        
    // Restricts the entry of characters to digits (including hex), the negative sign,
        
    // the decimal point, and editing keystrokes (backspace).
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            
    base.OnKeyPress(e);

            NumberFormatInfo numberFormatInfo 
    = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
            
    string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
            
    string groupSeparator = numberFormatInfo.NumberGroupSeparator;
            
    string negativeSign = numberFormatInfo.NegativeSign;

            
    string keyInput = e.KeyChar.ToString();

            
    if (Char.IsDigit(e.KeyChar))
            {
                
    // Digits are OK
            }
            
    else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
             keyInput.Equals(negativeSign))
            {
                
    // Decimal separator is OK
            }
            
    else if (e.KeyChar == '\b')
            {
                
    // Backspace key is OK
            }
            
    //    else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
            
    //    {
            
    //     // Let the edit control handle control and alt key combinations
            
    //    }
            else if (this.allowSpace && e.KeyChar == ' ')
            {

            }
            
    else
            {
                
    // Swallow this invalid key and beep
                e.Handled = true;
                
    //    MessageBeep();
            }
        }

        
    public int IntValue
        {
            
    get
            {
                
    return Int32.Parse(this.Text);
            }
        }

        
    public decimal DecimalValue
        {
            
    get
            {
                
    return Decimal.Parse(this.Text);
            }
        }

        
    public bool AllowSpace
        {
            
    set
            {
                
    this.allowSpace = value;
            }

            
    get
            {
                
    return this.allowSpace;
            }
        }
    }

      

  • 相关阅读:
    其实Unix很简单
    路由器硬件和操作系统软件关系之我见
    80后的我们
    虚拟机虚拟网卡作用
    [转]Cisco小失误,大麻烦
    DDWRT让我们的无线路由器用上Linux
    2011年全国大学生电子设计竞赛试题来自官网
    太网帧结构详解
    TCP/IP网络编程之四书五经
    四种以太网数据包详解
  • 原文地址:https://www.cnblogs.com/Lisen/p/1622555.html
Copyright © 2011-2022 走看看