I'm getting an unhandled exception on my Add program

357mag

Well-known member
Joined
Mar 31, 2023
Messages
58
Programming Experience
3-5
This program inputs two integers and then the user can choose to Add them or Subtract them. I'm using a Visual C# book by Joyce Farrell. But when I run the program I'm getting an unhandled exception error.

Unable to cast object of type "System.Windows.Forms.Textbox to type System.Convertible.

My code is this:
C#:
 private void buttonAdd_Click(object sender, EventArgs e)
        {
            int firstNumber;
            int secondNumber;
            int sum;

            firstNumber = Convert.ToInt32(textBoxFirstNumber);
            secondNumber = Convert.ToInt32(textBoxSecondNumber);

            sum = firstNumber + secondNumber;

            labelAnswer.Text = "The sum is " + sum;
        }
 

Attachments

  • Exception.jpg
    Exception.jpg
    131.8 KB · Views: 7
Last edited by a moderator:
I fixed it. I keep forgetting the .text at the end of Convert.ToInt32(textBoxfirstNumber)

I keep forgetting that last part needs to be (textBoxFirstNumber.Text)
 
There is something I spotted in my code that baffles me:
C#:
 private void buttonSubtract_Click(object sender, EventArgs e)
        {
            int firstNumber;
            int secondNumber;
            int difference;

            firstNumber = Convert.ToInt32(textBoxFirstNumber.Text);
            secondNumber = Convert.ToInt32(textBoxSecondNumber.Text);
        }
My variables are firstNumber and secondNumber. But Visual Studio insists that I use textBoxSecondNumber or textBoxFirstNumber. The capitalization is different. The drop-down menu even shows that next to the text I'm writing in the editor.

I don't get that.
 
Last edited by a moderator:
Welcome to the forum. In the future please put your code in code tags. Easiest way to do that is to use the icon on the toolbar that looks like </>
 
Anyway VS is just making a guess as to what you may want to do. It's not really insisting. You can turn off IntelliSense and the code suggestions of it annoys you.
 

Latest posts

Back
Top Bottom