检查TextBox输入是否为十进制数字-C#

本文关键字:十进制数字 -C# 是否 TextBox 输入 检查 | 更新日期: 2023-09-27 18:29:01

我的目标:我希望文本框接受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
        }
    } 
}

我是一个新手,谢谢你提前的帮助

检查TextBox输入是否为十进制数字-C#

使用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`
        }