簡體   English   中英

文本框只接受C#中的數字

[英]Text box to accept only number in C#

我正在使用法語鍵盤。 在頂部鍵盤上有鍵,如&,é,“,”,(, - ,è,_,ç,à)使用它作為數字我必須按shift或打開大寫鎖定。

我可以在24中放入文本框的最大數量。

上限為:我可以輸入數字。 關閉capLock:我不能使用shift來輸入數字。

我也可以在文本框中輸入&,é,“,',(, - ,è,_,ç,à等值。

public class NumericalTextBox : TextBox
    {
        private int MaxValue;

        public NumericalTextBox()
        {
        }
        public NumericalTextBox(int max_value)
        {
            MaxValue = max_value;
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    if (e.KeyCode != Keys.Back)
                    {
                        e.SuppressKeyPress = true;
                    }
                }
            }
            if (Control.ModifierKeys == Keys.Shift)
            {
                e.SuppressKeyPress = true;
            }

        }
        protected override void OnKeyPress(KeyPressEventArgs e)
        {

            if (MaxValue >= 0 && !char.IsControl(e.KeyChar) && char.IsDigit(e.KeyChar))
            {
                try
                {
                    string s = this.Text + e.KeyChar;
                    int x = int.Parse(s);
                    if (x >= MaxValue)
                        e.Handled = true;
                }
                catch
                {
                    //e.Handled = true;
                }
            }
            base.OnKeyPress(e);
        }


    }
}

如果可以,請改用NumericUpDown -Control。 它為您提供了所希望的行為(過濾非數字值)。

但是,如果必須使用文本框,則Shtako-verflow的注釋指向答案。

最佳答案的代碼:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
        && !char.IsDigit(e.KeyChar) 
        && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // only allow one decimal point
    if (e.KeyChar == '.' 
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }
}

有一種簡單的方法可以實現這一目標。 您可以使用正則表達式驗證器。

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ValidationExpression="^[0-9]+$"
        ErrorMessage="Only Numbers" ControlToValidate="TextBox2"></asp:RegularExpressionValidator> 

這將幫助您只接受Textbox的整數值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM