The function of the form is that if I put a number in the text box and click the add button, the label shows the number. Then, if I put another number in the text box and click the add button, the label shows the sum of those two numbers.
Example:
If I put 10 in the text box and click the add button, the label shows 10.
Then I put 8 in the text box and click the add button; the label shows 10 + 8 = 18.
Then I put 2 in the text box and click the add button; the label shows 18 + 2 = 20.
I created the form application, but it is not working correctly.
Can anyone please give me a solution to this problem?
namespace ICT_Project_Prac
{
public partial class Form1 : Form
{
private int sum;
public Form1()
{
InitializeComponent();
sum = 0;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sum = int.Parse(textBox1.Text);
sum = +sum;
label1.Text = sum.ToString();
}
catch
{
MessageBox.Show("Please Ender The Valid Number");
}
}
}
}
2
Answers
Your problem is that you allways put "sum = int.Parse(textBox1.Text);" so you loose your "sum" value before you sum with the new value.
You should do this.
first thing you are adding new value to the sum wrong if you want to add a value to the current value of a variable you can use on of these methods
lets say you want to add 2 to sum:
as for the way you should read the value inside of the text box and add it to the sum:
here is what’s wrong with your code: