C# 检查文本框的值是否不是数字[重复]

问题描述 投票:0回答:1

这是我的代码:

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

我想从文本框中读取值并将其转换为双精度函数。小数点后应输入一个点,正如 double 函数中的用途一样。 但是,每当文本框中没有任何内容或除数字之外的字符时,就会出现错误消息。我怎么解决这个问题? 控制台的输出仅用于测试。

c# textbox numbers double
1个回答
0
投票

您可以使用

Double.TryParse
方法代替
Int32.Parse
。检查更新的代码:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.