簡體   English   中英

如何將 C# 中的文本框限制為僅接收數字和(點“。”或逗號“,”),在“。”之后或 "," 只允許 2 個數字字符

[英]How restrict textbox in C# to only receive numbers and (dot "." or comma ","), after "." or "," only allow 2 number characters

我正在嘗試開發一個代碼來限制使用 C# 的 TextBox 只允許輸入數字+逗號(“,”)或點(“。”)+點或逗號后僅 2 個數字所以這種方式可以查看可以輸入的可能數字:

3213,04 = OK
3211,664 = Not
32.31 = OK
32.3214 = Not
334,,00 = Not
3247,.00 = Not
214.,00 = Not
32.. = Not
8465,0 = Ok
654.0 = Ok

明白我的目標了嗎? 我開發了下面的代碼

private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
    if (txtValormetrocubico.TextLength >= 0 && (e.KeyChar == (char)Keys.OemPeriod || e.KeyChar == (char)Keys.Oemcomma))
    {
        //tests 
    }
    else
    {
        if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar)
            && e.KeyChar != '.' && e.KeyChar != ',')
        {
            e.Handled = true;
        }
        // only allow one decimal point
        if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }

        if (e.KeyChar == ','  && (sender as TextBox).Text.IndexOf(',') > -1)
        {
            e.Handled = true;
        }
    }
}

這是我寫的輔助功能

private bool alreadyExist(string _text , ref char KeyChar)
        {
            if (_text.IndexOf('.')>-1)
            {
                KeyChar = '.';
                return true;
            }
            if (_text.IndexOf(',') > -1)
            {
                KeyChar = ',';
                return true;
            }
            return false;
        }

這是您的按鍵事件處理程序

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

            //check if '.' , ',' pressed
            char sepratorChar='s';
            if (e.KeyChar == '.' || e.KeyChar == ',')
            {
                // check if it's in the beginning of text not accept
                if (txtValormetrocubico.Text.Length == 0) e.Handled = true;
                // check if it's in the beginning of text not accept
                if (txtValormetrocubico.SelectionStart== 0 ) e.Handled = true;
                // check if there is already exist a '.' , ','
                if (alreadyExist(txtValormetrocubico.Text , ref sepratorChar)) e.Handled = true;
                //check if '.' or ',' is in middle of a number and after it is not a number greater than 99
                if (txtValormetrocubico.SelectionStart != txtValormetrocubico.Text.Length && e.Handled ==false)
                {
                    // '.' or ',' is in the middle
                    string AfterDotString = txtValormetrocubico.Text.Substring(txtValormetrocubico.SelectionStart);
                    
                    if (AfterDotString.Length> 2)
                    {
                        e.Handled = true;
                    }
                }
            }
            //check if a number pressed

            if (Char.IsDigit(e.KeyChar))
            {
                //check if a coma or dot exist
                if (alreadyExist(txtValormetrocubico.Text ,ref sepratorChar))
                {
                    int sepratorPosition = txtValormetrocubico.Text.IndexOf(sepratorChar);
                    string afterSepratorString = txtValormetrocubico.Text.Substring(sepratorPosition + 1 );
                    if (txtValormetrocubico.SelectionStart > sepratorPosition && afterSepratorString.Length >1)
                    {
                        e.Handled = true;
                    }
                   
                }
            }

            
        }

我認為你需要像 Masked Textbox control 這樣的東西,你有一些參考資料

http://msdn.microsoft.com/en-us/library/kkx4h3az.aspx http://www.c-sharpcorner.com/uploadfile/mahesh/maskedtextbox-in-C-Sharp/

做你想做的另一種方法是使用正則表達式

好吧,您可以創建一個通用函數並在keypress事件上調用它,此代碼是一個通用實例。

validate_textBox是一個通用函數

private void validate_textBox(TextBox _text, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                    && !char.IsDigit(e.KeyChar)
                    && e.KeyChar != '.' && e.KeyChar != ',')
            {
                e.Handled = true;
            }
            if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.' && e.KeyChar != ',')
            {
                e.Handled = true;
            }

            //check if '.' , ',' pressed
            char sepratorChar = 's';
            if (e.KeyChar == '.' || e.KeyChar == ',')
            {
                // check if it's in the beginning of text not accept
                if (_text.Text.Length == 0) e.Handled = true;
                // check if it's in the beginning of text not accept
                if (_text.SelectionStart == 0) e.Handled = true;
                // check if there is already exist a '.' , ','
                if (alreadyExist(_text.Text, ref sepratorChar)) e.Handled = true;
                //check if '.' or ',' is in middle of a number and after it is not a number greater than 99
                if (_text.SelectionStart != _text.Text.Length && e.Handled == false)
                {
                    // '.' or ',' is in the middle
                    string AfterDotString = _text.Text.Substring(_text.SelectionStart);

                    if (AfterDotString.Length > 2)
                    {
                        e.Handled = true;
                    }
                }
            }
            //check if a number pressed

            if (Char.IsDigit(e.KeyChar))
            {
                //check if a coma or dot exist
                if (alreadyExist(_text.Text, ref sepratorChar))
                {
                    int sepratorPosition = _text.Text.IndexOf(sepratorChar);
                    string afterSepratorString = _text.Text.Substring(sepratorPosition + 1);
                    if (_text.SelectionStart > sepratorPosition && afterSepratorString.Length > 1)
                    {
                        e.Handled = true;
                    }

                }
            }
        } 

然后,您可以為表單中的每個文本框調用類似此代碼的函數

        private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
        {
            validate_textBox(sender as TextBox, e);
        }
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            validate_textBox(sender as TextBox, e);
        }

我不知道誰在 2021 年尋找這個,但這是一種覆蓋 ontextchange 事件的解決方案! 干杯

  protected override void OnTextChanged(EventArgs e)
    {
   
        base.OnTextChanged(e);
        String text = "";

        Char[] chars = this.Text.ToString().ToCharArray();

        int total_dots = 0;
        int dot_pos = 0;

        int char_pos = 0;

        foreach (Char c in chars )
        {
            char_pos++;
           
            if (Char.IsDigit(c))
            {

                if(dot_pos > 0) { //dot already exists
                    
                    if (char_pos <= dot_pos + 2)  //only accept two numbers after dot (3.99)
                    {
                        text += c.ToString();
                    }

                }
                else
                {
                    text += c.ToString();
                }

               
            }

            if(c == '.' || c == ',')
            {
                total_dots++;

                if (char_pos > 1 && total_dots <=1)   //only accept one dot and if the dot is not in first position
                {
                    text += c.ToString();
                    dot_pos = char_pos;
                }
            }

        }

        this.Text = text;
        this.SelectionStart = this.Text.Length;

    }

暫無
暫無

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

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