字符串

时间:2015-05-21 17:13:53

标签: c# exception visual-studio-2013 windows-forms-designer

我试图调试这个,我无法弄清楚它有什么问题。 我试图建立一个计算器,但我不断收到这个错误。

  double currentResult = 0;

        int stringLengthStarter = 0;
        int stringLengthCounter = 0;

        public Form1()
        {
            InitializeComponent();
        }

        // Appends the numbers to the text box when the buttons are clicked

        private void button1_Click(object sender, EventArgs e) // Click on the digit 1
        {
            if (clearingTextBoxFlag)
            {
                textBox1.Clear();
            }
            stringLengthCounter++;
            textBox1.AppendText("1");
            clearingTextBoxFlag = false;
        }


 private void plusButton_Click(object sender, EventArgs e) // Plus button clicked
        {
            pick = 1; // 1 - Plus operation
            currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter));
            stringLengthStarter = stringLengthCounter + 1;
            stringLengthCounter = 0;
            textBox1.AppendText("+");
        }

 private void equalsButton_MouseClick(object sender, MouseEventArgs e) // Mouse click on the equals button
        {
            textBox1.Clear();
            if (pick == 1) // Plus operation
            {
                checkTextBox.Text = textBox1.Text;
                currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter)); // The problem
                textBox1.Text = "" + currentResult;
            }

我试图做1 + 1 =并且它在此行获得了执行:currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter)); //问题

1 个答案:

答案 0 :(得分:1)

在你的equalsButton_MouseClick方法中,你要做的第一件事是清除textBox1,它将textBox1.Text设置为string.Empty。之后,您尝试创建textBox1.Text的子字符串,但字符串的长度为0,这就是您的方法崩溃的原因。它正在尝试访问不再存在的字符串的索引。

尝试在方法结束时移动textBox1.Clear。