4

我是 Windows 8 手机的新手。我正在编写一个计算器应用程序,它只能接受文本框中的数字和一个小数点。如何防止用户在文本框中输入两个或多个小数点,因为计算器无法处理。

我一直在使用 Keydown Event,这是最好的还是应该使用 Key up?

private void textbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {

}
4

14 回答 14

4

您还可以将 RegExp 与TextChanged事件一起使用:下面的代码片段将处理任何整数和浮点数,包括正数和负数

    string previousInput = "";
    private void InputTextbox_TextChanged(object sender, RoutedEventArgs e)
    {
        Regex r = new Regex("^-{0,1}\d+\.{0,1}\d*$"); // This is the main part, can be altered to match any desired form or limitations
        Match m = r.Match(InputTextbox.Text);
        if (m.Success)
        {
            previousInput = InputTextbox.Text;
        }
        else
        {
            InputTextbox.Text = previousInput;
        }
    }
于 2013-11-04T14:30:02.433 回答
4

您可以将其用于 KeyPress Event 为 form.Designer 中的文本框设置按键事件,如下所示

this.yourtextbox.KeyPress +=new System.Windows.Forms.KeyPressEventHandler(yourtextbox_KeyPress);

然后在你的表单中使用它

//only number And single decimal point input فقط عدد و یک ممیز میتوان نوشت
        public void onlynumwithsinglepoint(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.'))
            { e.Handled = true; }
            TextBox txtDecimal = sender as TextBox;
            if (e.KeyChar == '.' && txtDecimal.Text.Contains("."))
            {
                e.Handled = true;
            }
        }

然后

private void yourtextbox_KeyPress(object sender, KeyPressEventArgs e)
        {
            onlynumwithsinglepoint(sender, e);
        }
于 2015-01-22T15:08:46.470 回答
2

我曾经在 .NET 2 天内广泛使用它,不确定它是否仍然有效。支持可配置的精度、货币、负数并处理所有输入方法。

using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace System.Windows.Forms
{
    public class NumericTextBox : TextBox
    {
        private System.ComponentModel.Container components = null;

        private bool _AllowNegatives = true;
        private int _Precision = 0;
        private char _CurrencyChar = (char)0;
        private bool _AutoFormat = true;
        private decimal _MinValue = Decimal.MinValue;
        private decimal _MaxValue = Decimal.MaxValue;

        /// <summary>
        /// Indicates if the negative values are allowed.
        /// </summary>
        [DefaultValue(true), RefreshProperties(RefreshProperties.All), Description("Indicates if the negative values are allowed."), Category("Behavior")]
        public bool AllowNegatives
        {
            get
            {
                return this._AllowNegatives;
            }
            set
            {
                this._AllowNegatives = value;

                if (!value)
                {
                    if (this._MinValue < 0) this._MinValue = 0;
                    if (this._MaxValue < 1) this._MaxValue = 1;
                }
            }
        }
        /// <summary>
        /// Indicates the maximum number of digits allowed after a decimal point.
        /// </summary>
        [DefaultValue(0), Description("Indicates the maximum number of digits allowed after a decimal point."), Category("Behavior")]
        public int Precision
        {
            get
            {
                return this._Precision;
            }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("Precision", value.ToString(), "The value of precision must be an integer greater than or equal to 0.");
                }
                else
                {
                    this._Precision = value;
                }
            }
        }
        /// <summary>
        /// Gets or sets the character to use as a currency symbol when validating input.
        /// </summary>
        [DefaultValue((char)0), Description("Gets or sets the character to use as a currency symbol when validating input."), Category("Behavior")]
        public char CurrencyChar
        {
            get
            {
                return this._CurrencyChar;
            }
            set
            {
                this._CurrencyChar = value;
            }
        }
        /// <summary>
        /// Indicates if the text in the textbox is automatically formatted. Missing currency symbols and trailing spaces are added where applicable.
        /// </summary>
        [DefaultValue(true), Description("Indicates if the text in the textbox is automatically formatted. Missing currency symbols and trailing spaces are added where applicable."), Category("Behavior")]
        public bool AutoFormat
        {
            get
            {
                return this._AutoFormat;
            }
            set
            {
                this._AutoFormat = value;
            }
        }
        /// <summary>
        /// Gets or sets the numerical value of the textbox.
        /// </summary>
        [Description("Gets or sets the numerical value of the textbox."), Category("Data")]
        public decimal Value
        {
            get
            {
                if (this.Text.Length == 0)
                {
                    return (decimal)0;
                }
                else
                {
                    return decimal.Parse(this.Text.Replace(this.CurrencyChar.ToString(), ""));
                }
            }
            set
            {
                if (value < 0 && !this.AllowNegatives)
                {
                    throw new ArgumentException("The specified decimal is invalid, negative values are not permitted.");
                }

                this.Text = this.FormatText(value.ToString());
            }
        }
        /// <summary>
        /// Gets or sets the maximum numerical value of the textbox.
        /// </summary>
        [RefreshProperties(RefreshProperties.All), Description("Gets or sets the maximum numerical value of the textbox."), Category("Behavior")]
        public decimal MaxValue
        {
            get
            {
                    return this._MaxValue;
            }
            set
            {
                if (value <= this._MinValue)
                {
                    throw new ArgumentException("The Maximum value must be greater than the minimum value.", "MaxValue");
                }
                else
                {
                    this._MaxValue = Decimal.Round(value, this.Precision);
                }
            }
        }
        /// <summary>
        /// Gets or sets the minimum numerical value of the textbox.
        /// </summary>
        [RefreshProperties(RefreshProperties.All), Description("Gets or sets the minimum numerical value of the textbox."), Category("Behavior")]
        public decimal MinValue
        {
            get
            {
                return this._MinValue;
            }
            set
            {
                if (value < 0 && !this.AllowNegatives)
                {
                    throw new ArgumentException("The Minimum value cannot be negative when AllowNegatives is set to false.", "MinValue");
                }
                else if (value >= this._MaxValue)
                {
                    throw new ArgumentException("The Minimum value must be less than the Maximum value.", "MinValue");
                }
                else
                {
                    this._MinValue = Decimal.Round(value, this.Precision);
                }
            }
        }

        /// <summary>
        /// Create a new instance of the NumericTextBox class with the specified container.
        /// </summary>
        /// <param name="container">The container of the control.</param>
        public NumericTextBox(System.ComponentModel.IContainer container)
        {
            ///
            /// Required for Windows.Forms Class Composition Designer support
            ///
            container.Add(this);
            InitializeComponent();
        }
        /// <summary>
        /// Create a new instance of the NumericTextBox class.
        /// </summary>
        public NumericTextBox()
        {
            ///
            /// Required for Windows.Forms Class Composition Designer support
            ///
            InitializeComponent();
        }

        #region Component Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            // 
            // NumericTextBox
            // 
            this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.NumericTextBox_KeyPress);
            this.Validating += new System.ComponentModel.CancelEventHandler(this.NumericTextBox_Validating);

        }
        #endregion

        /// <summary>
        /// Checks to see if the specified text is valid for the properties selected.
        /// </summary>
        /// <param name="text">The text to test.</param>
        /// <returns>A boolean value indicating if the specified text is valid.</returns>
        protected bool IsValid(string text)
        {
            Regex check = new Regex("^" + ((this.AllowNegatives && this.MinValue < 0) ? (@"\-?") : "") + ((this.CurrencyChar != (char)0) ? (@"(" + Regex.Escape(this.CurrencyChar.ToString()) + ")?") : "") + @"\d*" + ((this.Precision > 0) ? (@"(\.\d{0," + this.Precision.ToString() + "})?") : "") + "$");

            if (!check.IsMatch(text)) return false;
            if (text == "-" || text == this.CurrencyChar.ToString() || text == "-" + this.CurrencyChar.ToString()) return true;

            Decimal val = Decimal.Parse(text);

            if (val < this.MinValue) return false;
            if (val > this.MaxValue) return false;

            return true;
        }
        /// <summary>
        /// Formats the specified text into the configured number format.
        /// </summary>
        /// <param name="text">The text to format.</param>
        /// <returns>The correctly formatted text.</returns>
        protected string FormatText(string text)
        {
            string format = "{0:" + this.CurrencyChar.ToString() + "0" + ((this.Precision > 0) ? "." + new String(Convert.ToChar("0"), this.Precision) : "") + ";-" + this.CurrencyChar.ToString() + "0" + ((this.Precision > 0) ? "." + new String(Convert.ToChar("0"), this.Precision) : "") + "; £0" + ((this.Precision > 0) ? "." + new String(Convert.ToChar("0"), this.Precision) : "") + "}";
            return String.Format(format, text).Trim();
        }
        /// <summary>
        /// Overrides message handler in order to pre-process and validate pasted data.
        /// </summary>
        /// <param name="m">Message</param>
        protected override void WndProc(ref Message m) 
        {
            switch (m.Msg)
            {
                case 0x0302:
                    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
                    {
                        string paste = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
                        string text = this.Text.Substring(0, this.SelectionStart) + paste + this.Text.Substring(this.SelectionStart + this.SelectionLength);

                        if (this.IsValid(text))
                        {
                            base.WndProc(ref m);
                        }
                    }
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        protected override void Dispose(bool disposing)
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        private void NumericTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (Char.IsNumber(e.KeyChar) || 
                (this.AllowNegatives && e.KeyChar == Convert.ToChar("-")) || 
                (this.Precision > 0 && e.KeyChar == Convert.ToChar(".")) || 
                e.KeyChar == this.CurrencyChar)
            {
                string text = this.Text.Substring(0, this.SelectionStart) + e.KeyChar.ToString() + this.Text.Substring(this.SelectionStart + this.SelectionLength);
                if (!this.IsValid(text))
                {
                    e.Handled = true;
                }
            }
            else if (!Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        private void NumericTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.Text.Length == 0)
            {
                this.Text = this.FormatText("0");
            }
            else if (this.IsValid(this.Text))
            {
                this.Text = this.FormatText(this.Text);
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}
于 2013-11-06T18:22:43.893 回答
1

简单

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;
        decimal x;
        if (ch == (char)Keys.Back)
        {
            e.Handled = false;
        }
        else if (!char.IsDigit(ch) && ch != '.' || !Decimal.TryParse(textBox1.Text+ch, out x) )
        {
            e.Handled = true;
        }
    }
于 2015-07-16T12:09:16.603 回答
1

需要验证的清单

  • 停止多个点 Char
  • 停止第一个字符作为点输入
  • 停止允许除数字和控制以外

按键事件

private void txtEstimate_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '.' && txtEstimate.Text.Contains("."))
    {
        // Stop more than one dot Char
        e.Handled = true;
    }
    else if (e.KeyChar == '.' && txtEstimate.Text.Length == 0)
    {
        // Stop first char as a dot input
        e.Handled = true;
    }
    else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        // Stop allow other than digit and control
        e.Handled = true;
    }
}

低于输入验证

  • 0.1 - 有效
  • .1 - 无效
  • 12..1 - 无效
  • 12.36 - 有效
  • 123.2548 - 有效
于 2018-06-27T08:47:20.847 回答
1
private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
        {
            // Allow Digits and BackSpace char
        }
        else if (e.KeyChar == '.' && !((TextBox)sender).Text.Contains('.'))
        {
            //Allows only one Dot Char
        }
        else
        {
            e.Handled = true;
        }
    }
于 2016-06-17T07:29:35.350 回答
0

对于数字 ==>ImputScope ="Number" 并且您可以通过解析例如 dat 来计算字符串中的字符点:

char[] c = yourstring.tocharArray();
int i = 0;
foreach var char in c
if(char.equals(".") or char.equals(",")
i++

if (i > 1)
MessageBox.Show("Invalid Number")

这段代码只是举例,但它是有效的。

于 2013-11-04T13:02:37.207 回答
0

谢谢大家的帮助。我终于做到了,它在 Text changed 事件中运行良好。那是在将 inputscope 设置为 Numbers 之后

string dika = Textbox1.Text;
    int countDot = 0;
    for (int i = 0; i < dika.Length; i++)
    {
        if (dika[i] == '.')
        {
            countDot++;
            if (countDot > 1)
            {
                dika = dika.Remove(i, 1); 
                i--;
                countDot--;
            }
        }
    }
Textbox1.Text = dika;
Textbox1.Select(dika.Text.Length, 0);
于 2013-11-07T18:51:24.287 回答
0

您可以使用数字文本框或

尝试这个

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
 {
if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
 {
  e.Handled = false;
 }
 else
 {
    e.Handled = true;
 }
}
于 2013-11-04T04:23:49.493 回答
0
private void txtDecimal_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar!='.')
    {
        e.Handled = true;
    }
    if (e.KeyChar == '.' && txtDecimal.Text.Contains("."))
    {
        e.Handled = true;
    }
}
于 2014-01-19T15:24:06.200 回答
0

看这个。这对我有用。

 private void txtParciales_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(txtParciales.Text, @"\d+(\.\d{2,2})"))
                e.Handled = true;
            else e.Handled = false;
        }
于 2015-06-17T17:40:51.413 回答
0

asp:RegularExpressionValidator用控制器试试这个

<asp:RegularExpressionValidator ID="rgx" 
ValidationExpression="[0-9]*\.?[0-9]" ControlToValidate="YourTextBox" runat="server" ForeColor="Red" ErrorMessage="Decimals only!!" Display="Dynamic"  ValidationGroup="lnkSave"></asp:RegularExpressionValidator>
于 2016-12-29T05:49:14.213 回答
0

this is what I used.

 private void txtBoxBA_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        // only allow 0-9 and "."
        e.Handled = !((e.Key.GetHashCode() >= 48 && e.Key.GetHashCode() <= 57));

        // check if "." is already there in box.
        if (e.Key.GetHashCode() == 190)
            e.Handled = (sender as TextBox).Text.Contains(".");
    }
于 2016-06-20T17:20:32.813 回答
0
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar != Convert.ToChar(Keys.Enter) && e.KeyChar != Convert.ToChar(Keys.Back) && e.KeyChar != Convert.ToChar(Keys.Delete) && e.KeyChar != '.' && e.KeyChar != '1' && e.KeyChar != '2' && e.KeyChar != '3' && e.KeyChar != '4' && e.KeyChar != '5' && e.KeyChar != '6' && e.KeyChar != '7' && e.KeyChar != '8' && e.KeyChar != '9' && e.KeyChar != '0')
        {
            e.Handled = true;
        }
        else
        {
            e.Handled = false;
        }

    }
于 2017-01-05T15:33:37.833 回答