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;
            }
        }
    }

      

  • 相关阅读:
    求解一元二次方程
    常用电脑软件
    c语言的布尔量
    unsigned int数据类型最大数
    int数据类型的最大数
    习题6-8 统计一行文本的单词个数
    习题6-6 使用函数输出一个整数的逆序数
    习题6-5 使用函数验证哥德巴赫猜想
    习题6-4 使用函数输出指定范围内的Fibonacci数
    C#委托、泛型委托
  • 原文地址:https://www.cnblogs.com/Lisen/p/1622555.html
Copyright © 2011-2022 走看看