我在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;
}发布于 2013-04-16 03:53:14
如果不可能进行转换,则应该调用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");发布于 2013-04-16 03:53:02
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
Decimal temp;
if (!Decimal.TryParse(out temp, tempC.Text))
return;
...发布于 2013-04-16 03:56:58
试试这个:
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
if(tempC.Text = "")
return;
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);
}https://stackoverflow.com/questions/16023616
复制相似问题