C# check if a value of a Textbox isn´t a number [duplicate]

This is my Code:

double Input = 0;

private void ziel_TextChanged(object sender, EventArgs e)
{
    if (ziel.Text != null)
    {
        Input = Int32.Parse(ziel.Text);
    }
    else MessageBox.Show("text = null");
    Console.WriteLine(Input);
}

I want to read the value from the TextBox and convert it into a double function. After the decimal point, a point should be entered, as it is intended in the double function.
But whenever there is nothing in the TextBox or a character other than a number, an error message appears. How can I solve this problem?
The output to the console is only for testing.

  • 1

    Does this answer your question? Converting string to double in C#, use double.TryParse(<string value>) to safely parse from string to number. Also depends on your application, is it a WebForm? If yes, you can apply type="number" to restrict the text box for inputting number/floating-point number.

    – 




You can use Double.TryParse method instead of Int32.Parse. Check the updated code:

double Input = 0;

private void ziel_TextChanged(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(ziel.Text))
    {
        if (double.TryParse(ziel.Text, out double result))
        {
            Input = result;
        }
        else
        {
            Console.WriteLine("Invalid input. Please enter a valid number.");
        }
    }
    else
    {
        // Handle empty text box scenario here if needed
        Console.WriteLine("Text box is empty.");
    }

    Console.WriteLine(Input);
}

Leave a Comment