运行我在'if'语句之间放置的代码时,我的程序失败了。 我知道为什么过分依赖一项任务就是检测到 数字< 10或> 9 高于9的数字有效,但是带有一位数的数字将导致此位置出现异常:
str = textBox23.Text;
retString = str.Substring(1, 1);
textBox22.Text = retString;
我猜测if / else编写得不好,但是我已经检查了不同的变量,但它没有用。我真的不知道发生了什么 这是代码:
private void button10_Click_1(object sender, EventArgs e)
{
if (textBox23.Text == "" || Int32.Parse(textBox23.Text) > 9)
{
double L1 = double.Parse(textBox13.Text);
double L2 = double.Parse(textBox16.Text);
double wynik = L1 - L2;
textBox23.Text = wynik.ToString();
string str = null;
string retString = null;
str = textBox23.Text;
retString = str.Substring(0, 1);
textBox21.Text = retString;
str = textBox23.Text;
retString = str.Substring(1, 1);
textBox22.Text = retString;
}
else if (textBox23.Text == "" || Int32.Parse(textBox23.Text)
< 10)
{
double L1 = double.Parse(textBox13.Text);
double L2 = double.Parse(textBox16.Text);
double wynik = L1 - L2;
textBox23.Text = wynik.ToString();
string str = null;
string retString = null;
str = textBox23.Text;
retString = str.Substring(0, 1);
textBox21.Text = retString;
}
答案 0 :(得分:2)
您正在更改textbox23的值
textBox23.Text = wynik.ToString();
任何机会这个值都不是2个字符长,因为后者你做
str = textBox23.Text;
retString = str.Substring(1, 1);
由于substring是从零开始的字符,如果它不是至少2个字符,你会得到一个错误
答案 1 :(得分:0)
你可以使用tryParse
private void button10_Click_1(object sender, EventArgs e)
{
Int32 IsAnumber;
if(Int32.TryParse(textBox23.Text, out IsAnumber)
{
if (IsAnumber > 9)
{
double L1 = double.Parse(textBox13.Text);
double L2 = double.Parse(textBox16.Text);
double wynik = L1 - L2;
textBox23.Text = wynik.ToString();
string str = null;
string retString = null;
str = textBox23.Text;
retString = str.Substring(0, 1);
textBox21.Text = retString;
str = textBox23.Text;
retString = str.Substring(1, 1);
textBox22.Text = retString;
}
else
{
double L1 = double.Parse(textBox13.Text);
double L2 = double.Parse(textBox16.Text);
double wynik = L1 - L2;
textBox23.Text = wynik.ToString();
string str = null;
string retString = null;
str = textBox23.Text;
retString = str.Substring(0, 1);
textBox21.Text = retString;
}
}
答案 2 :(得分:0)
不清楚你想要获得什么,但是我会选择这个
int int23 = 0;
if (!int.TryParse(textBox23.Text, out int23))
{
// manage error and exit function (via exception or return), test in here also string.Empty for textBox23.
}
if (int23 > 9)
{
// Do What you need
}
else if (int23 < 10)
{
// Do What you need
}
但是一旦你得到了int变量,你可以直接格式化它们。
答案 3 :(得分:0)
这样的东西看起来与你想要实现的类似
private void button10_Click_1(object sender, EventArgs e)
{
double box23;
if (double.TryParse(textBox23.Text, out box23))
{
double L1 = double.Parse(textBox13.Text);
double L2 = double.Parse(textBox16.Text);
double wynik = L1 - L2;
textBox23.Text = wynik.ToString();
string str = textBox23.Text;
string retString = str.Substring(0, 1);
textBox21.Text = retString;
if (box23 > 9)
{
str = textBox23.Text;
retString = str.Substring(1, 1);
textBox22.Text = retString;
}
}
}