Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
good morning,

i have three textboxes for firstnumber,secondnumber and result.

I have 4 buttons addition,subtraction,multiplication and division.


if i enter firstnumber and secondnumber and press on any button the result should be displayed on the result textbox.

i.e. if i enter 4 in first textbox and 4 in second textbox and click on add button the result of 8 should be displayed on result textbox.

i am giving my code

C#
protected void Page_Load(object sender, EventArgs e)
   {
   }
   protected void btnadd_Click(object sender, EventArgs e)
   {
       txtresult.Text = (txtfirstnumber.Text) + (txtsecondnumber.Text);
   }
   protected void btnsubtraction_Click(object sender, EventArgs e)
   {
       txtresult.Text = (txtfirstnumber.Text) - (txtsecondnumber.Text);
   }
   protected void btnmultiplication_Click(object sender, EventArgs e)
   {
       txtresult.Text = (txtfirstnumber.Text) * (txtsecondnumber.Text);
   }
   protected void btndivision_Click(object sender, EventArgs e)
   {
       txtresult.Text = (txtfirstnumber.Text) * (txtsecondnumber.Text);
   }


please help me.

thank you.
Posted

The Text property of a TextBox is a string - so adding them together doesn't work ("4" + "4" = "44")

So you need to convert the string to a number.

Lets assume you are using integers.

you can do

C#
int number1, number2;
if (int.TryParse(txtFirstNumnebr.Text, out number1) && (int.TryParse(txtSecondNumber.Text, out number2))
{
    int result = number1 + number2;

    txtresult.Text  = result.ToString();
}


int.TryParse attempts to convert teh string to an integer, returning false if it fails, or true if it works, and puts the result in the out parameter (number1 or number2)

I've shown an 'ADD' example - the same would need to be done for all the other operations too

Of course you could vastly improve on that by adding validation first, with error messages etc. - but at the level I am guessing you are at from your question, this should get you started.
 
Share this answer
 
txtfirstnumber.Text is System.String.
For arithmatic use Convert.ToDouble(somestring) or double.TryParse(somestring, out value). Or eny other types need you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900