Sunday, 30 September 2012

C#(Sharp) code to find sum of 2 numbers from 2 text boxes

C# Code for Find Sum Of 2  Numbers (textbox)

it is very easy find sum of two numbers in C# .for adding 2 numbers in C# we have 3 textBoxes,3 Labels
and a Button.Firstly create a new project or a website in visual studio .insert 3 TextBoxes,3 Labels and a Button.select the first TextBox and change the name to  textBoxFirstNumber,select the second TextBox and change the name to textBoxSecondNumber,select third TextBox and change the name to textBoxSum ,set labelboxes name as First Number,Second Number Sum approximately and set the name of Button as buttonFindSum.after that your form looks like this

this is my forms design in this the bottom textbox have the sum of 2 text boxes this will add by clicking sum button and print the result


after creating the page double click on Sum Button and type the following codes

C#shap Code

private void buttonFindSum_Click(object sender, EventArgs e)
        {
            int firstNumber, secondNumber, sum; // to save numbers 

            firstNumber = Convert.ToInt32(textBoxFirstNumber.Text); //saves the first number into the variable
            secondNumber=Convert.ToInt32(textBoxSecondNumbe.Text ); //saves the second number into a            
            variable

            sum = firstNumber + secondNumber; //add two numbers

             textBoxSum.Text = sum.ToString();  // stores the sum to the third textbox(result),the variable sum is   
            in the datatype integer so we have to convert integer to string because the TextBox only accepts      
            string       variables and data
        }

We can simply write it 

 private void buttonFindSum_Click(object sender, EventArgs e)
        {
            textBoxSum.Text  = (Convert.ToInt32(textBoxFirstNumber.Text ) +    
           Convert.ToInt32(textBoxSecondNumber.Text)).ToString();