当TextBox中没有数字时,C#程序崩溃

Mal*_*arp 1 c# validation

我在C#中有一个WPF应用程序,对于我的一个文本框,输入然后自动转换(Celsius到Fahrenheit).当你输入一个数字,它工作正常,但一旦删除输入数字的所有数字,程序崩溃.我想这是因为输入格式是'无效',因为它只是试图转换什么?我对如何解决这个问题感到困惑,任何帮助都将不胜感激,谢谢!

这是我在应用程序中的代码:

private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
    tempC.MaxLength = 3;
    Temperature T = new Temperature(celsius);
    T.temperatureValueInCelcius = Convert.ToDecimal(tempC.Text);
    celsius = Convert.ToDecimal(tempC.Text);
    T.ConvertToFarenheit(celsius);
    tempF.Text = Convert.ToString(T.temperatureValueInFahrenheit);
}
Run Code Online (Sandbox Code Playgroud)

这是我创建的API的代码:

public decimal ConvertToFarenheit(decimal celcius)
{
    temperatureValueInFahrenheit = (celcius * 9 / 5 + 32);

    return temperatureValueInFahrenheit;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 5

您应该调用Decimal.TryParse方法,该方法尝试转换值并在无法进行转换时发出信号.

if(Decimal.TryParse(tempC.Text, out celsius))
{
   // Value converted correctly
   // Now you can use the variable celsius 

}
else
   MessageBox.Show("The textbox cannot be converted to a decimal");
Run Code Online (Sandbox Code Playgroud)