我在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);
}
这是我创建的API的代码:
public decimal ConvertToFarenheit(decimal celcius)
{
temperatureValueInFahrenheit = (celcius * 9 / 5 + 32);
return temperatureValueInFahrenheit;
}
答案 0 :(得分: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");
答案 1 :(得分:2)
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
Decimal temp;
if (!Decimal.TryParse(out temp, tempC.Text))
return;
...
答案 2 :(得分:0)
试试这个:
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);
}
答案 3 :(得分:0)
试试Decimal.TryParse
这是一些例子
string value;
decimal number;
// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a floating-point value with a currency symbol and a
// thousands separator.
value = "$1,643.57";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse value in exponential notation.
value = "-1.643e6";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a negative integer value.
value = "-1689346178821";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// The example displays the following output to the console:
// 1643.57
// Unable to parse '$1,643.57'.
// Unable to parse '-1.643e6'.
// -1689346178821