在输入数字后,我在某些textboxes
内做了一些简单的计算。如果代码是单位数字,代码工作正常。
但如果数字是两位数(例如10以上),则无法再次运行计算。
我不确定这是否是因为使用了TextChanged,但任何帮助都会很棒!
我的代码是:
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.Length == 0)
{
}
else if (textBox4.Text.Length == 0)
{
percentage = Convert.ToDouble(textBox2.Text);
percentage = double.Parse(textBox2.Text);
percentage1 = percentage / 100;
percentagecalc = percentage * total_loss;
rate = percentagecalc / 0.5;
rateString = System.Convert.ToString(rate);
textBox4.Text = rateString;
volume = rate * 0.5;
volumeString = System.Convert.ToString(volume);
textBox5.Text = volumeString;
}
if (textBox2.Text.Length == 0)
{
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
}
}
答案 0 :(得分:2)
不是Length
检查,而是TryParse
:
private void textBox2_TextChanged(object sender, EventArgs e) {
double p;
if (double.TryParse(textBox2.Text, out p)) {
// textBox2.Text has been changed and it contains double value - p
percentage = p;
percentage1 = percentage / 100;
percentagecalc = percentage * total_loss;
rate = percentagecalc / 0.5;
rateString = System.Convert.ToString(rate);
textBox4.Text = rateString;
volume = rate * 0.5;
volumeString = System.Convert.ToString(volume);
textBox5.Text = volumeString;
}
else {
// textBox2.Text has been changed, but it can't be treated as double
// (it's empty or has some weird value like "bla-bla-bla")
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
}
}