簡體   English   中英

檢查TextBox輸入是否為十進制數字-C#

[英]Check if TextBox input is a decimal number or not - C#

我的目標:我希望文本框接受十進制數字,例如123.45或0.45或1004.72。 如果用戶鍵入字母,例如a或b或c,程序將顯示一條消息,提醒用戶僅輸入數字。

我的問題:我的代碼僅檢查數字1003或567或1。它不檢查十進制數字123.45或0.45。 如何使我的文本框檢查十進制數字? 以下是我的代碼:

namespace Error_Testing
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string tString = textBox1.Text;
            if (tString.Trim() == "") return;
            for (int i = 0; i < tString.Length; i++)
            {
                if (!char.IsNumber(tString[i]))
                {
                    MessageBox.Show("Please enter a valid number");
                    return;
                }
            }
            //If it get's here it's a valid number
        }
    } 
}

我是新手,感謝您的提前幫助。 :)

使用Decimal.TryParse來檢查輸入的字符串是否為十進制。

decimal d;
if(decimal.TryParse(textBox1.Text, out d))
{
    //valid 
}
else
{
    //invalid
    MessageBox.Show("Please enter a valid number");
    return;
}

decimal.Tryparse對於包含“,”字符的字符串返回true,例如,類似“ 0,12”的字符串返回true。

private void txtrate_TextChanged_1(object sender, EventArgs e)
        {
            double parsedValue;
            decimal d;
            // That Check the Value Double or Not
            if (!double.TryParse(txtrate.Text, out parsedValue))
            {
                //Then Check The Value Decimal or double Becouse The Retailler Software Tack A decimal or double value
                if (decimal.TryParse(txtrate.Text, out d) || double.TryParse(txtrate.Text, out parsedValue))
                {
                    purchase();
                }
                else
                {
                    //otherwise focus on agin TextBox With Value 0
                    txtrate.Focus();                  
                    txtrate.Text = "0";                   
                }


            }
            else
            {
                // that function will be used for calculation Like 
                purchase();
                /*  if (txtqty.Text != "" && txtrate.Text != "")
                  {
                      double rate = Convert.ToDouble(txtrate.Text);
                      double Qty = Convert.ToDouble(txtqty.Text);
                      amt = rate * Qty;
                  }*/

            }`enter code here`
        }

暫無
暫無

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

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