Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

My Goal: I want textbox to accept the decimal numbers like 123.45 or 0.45 or 1004.72. If the user types in letters like a or b or c, the program should display a message alerting the user to input only numbers.

My Problem: My code only checks for numbers like 1003 or 567 or 1. It does not check for decimal numbers like 123.45 or 0.45. How do I make my text box check for decimal numbers? Following is my code:

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
        }
    } 
}

I am a newbie and Thanks for your help in advance. :)

like image 341
Smith Avatar asked Nov 30 '22 12:11

Smith


1 Answers

use Decimal.TryParse to check if the string entered is decimal or not.

decimal d;
if(decimal.TryParse(textBox1.Text, out d))
{
    //valid 
}
else
{
    //invalid
    MessageBox.Show("Please enter a valid number");
    return;
}
like image 151
user2711965 Avatar answered Dec 11 '22 18:12

user2711965