代码之家  ›  专栏  ›  技术社区  ›  Laurin Theisen

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

  •  0
  • Laurin Theisen  · 技术社区  · 2 年前

    这是我的代码:

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

    我想从TextBox中读取值,并将其转换为双函数。在小数点之后,应输入一个点,这是双功能中的预期值。 但是,每当TextBox中除了数字之外没有其他内容或字符时,就会出现一条错误消息。我该如何解决这个问题? 控制台的输出仅用于测试。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Amit Mohanty    2 年前

    您可以使用 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);
    }