Adithya Sai
Adithya Sai

Reputation: 1740

in c# i want to pass a variable from one button1 to other button2

I was trying to add 2 numbers by using a single text box (both the input and output must be specified in a single textbox).when I click on '+' button the data on the textbox1 should arise and and should enable the user to type a new number, those 2 numbers should be added and should be displayed when an '=' button is clicked

so my problem is:

if suppose if a button1 is clicked then a variable stored the value of that button1 and only displays that value when button2 is clicked

please help me in finding out

Upvotes: 0

Views: 854

Answers (3)

KSdev
KSdev

Reputation: 621

Ok, so one textbox that the user inputs a value into. One they use the + button the number disappears and they are able to put a second number in the textbox. The problem is you wish to store the value in the textbox prior to clearing it. This is easy, and should be handled in the Event Handler for the + button_click.

private int value1;
private int value2;
private int total;

private void addButton_Click(object sender, EventArgs e)
{
    int.TryParse(textbox1.Text, out value1);
}

private void equalButton_Click(object sender, EventArgs e)
{
    int.TryParse(textbox1.Text, out value2);
    total = value1 + value2;
    textbox1.Text = total.ToString();
}

Upvotes: 0

RacerNerd
RacerNerd

Reputation: 1579

If you have a value in a text field, when button 1 is clicked, the value from the text field must be extracted from the text field and saved somewhere. This is done in the click event handler for the button.

Depending on what type of a program you are working in, the place you save the info may be different. You may save this in a temporary variable, a database, the session, hidden field, or somewhere else, it just needs to be saved.

When button 2 is clicked, extract the value in the same way and save it somewhere. If you have two values in the designated saved locations when you click the '=' button, use these values, add them together, and populate the text box with the result.

Upvotes: 1

Selman Genç
Selman Genç

Reputation: 101681

You need just a variable to store first number.Define it in the class level:

int firstNumber;

Then when you get your number from textBox1 store it in the firstNumber,for example in button one (+) click:

int temp;
if(int.TryParse(textBox1.Text, out temp)
{  
   firtNumber = temp;
   textBox1.Clear(); // or set visible or enabled to false
}

In (=) button:

int temp;
if(int.TryParse(textBox2.Text, out temp)
{  
   label1.Text = String.Format("Result of {0} + {1} is : {2}",firstNumber, temp, firstnumber+temp);
}

Upvotes: 0

Related Questions