Harrison Ford

Harrison Ford

  • NA
  • 22
  • 966

TextBox input creates Exception : "Input string was...."

Dec 10 2014 3:19 PM
Hello :) 

I must say first that I'm new to C#. This code is not perfect but for now this is how I know to do it. I have 1 button 2 TextBoxes and 4 Lables, first 2 labels have some value and other 2 are result from addition in this case and it's working when I input values in both TextBoxes but when I try to input value in just one TextBox and click button I get Exception "Input string was not in a correct format.". So my question will be what I am doing wrong here ? How to make calculation for just one input value and not crash application? Thanks in advance.

http://prntscr.com/5fdc4g

Code: 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace teST
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        public void Calculate(TextBox A, Label B, Label C)
        {
            int a = Convert.ToInt32(A.Text);
            int b = Convert.ToInt32(B.Text);
            int c = a + b;
            C.Text = Convert.ToString(c);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Calculate(tbX, lblX, lblResult1);
            Calculate(tbY, lblY, lblResult2);

         }
    }

Attachment: form1.rar

Answers (2)