gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:32 25 4
gpt4 key购买 nike

我有一个 C# 中的 WPF 应用程序,对于我的一个文本框,输入被获取然后自动转换(摄氏度到华氏度)。当您输入一个数字时,它工作正常,但是一旦输入数字的所有数字都被删除,程序就会崩溃。我猜这是因为输入格式是“无效的”,因为它只是试图转换任何东西?我对如何解决这个问题感到困惑,我们将不胜感激,谢谢!

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

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

这是我创建的 API 的代码:

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

return temperatureValueInFahrenheit;
}

最佳答案

您应该调用方法 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");

关于当 TextBox 中没有数字时 C# 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16023616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com