I'm new to using C# and Visual Studio and i'm having a problem.
I'm trying to calculate a total value of three different multiplications using TextChanged event, so the total textbox updates every time I input a number in the textboxes I am using for the multiplications.
The total result in textbox4 is always 0. What am I doing wrong here?
Here is my code
public double multip_result1;
public double multip_result2;
public double multip_result3;
public void textbox1_TextChanged(object sender, EventArgs e)
{
double a, b, multip_result1;
a = Double.Parse(textbox1.Text);
b = 4.50;
multip_result1 = a * b;
total();
}
public void textbox2_TextChanged(object sender, EventArgs e)
{
double d, f, multip_result2;
d = double.Parse(textbox2.Text);
f = 6.50;
multip_result2 = d * f;
total();
}
public void textbox3_TextChanged(object sender, EventArgs e)
{
double h, j, multip_result3;
h = double.Parse(textbox3.Text);
j = 8.50;
multip_result3 = h * j;
total();
}
public void total()
{
double total_sum;
total_sum = multip_result1 + multip_result2 + multip_result3;
textbox4.Text = total_sum.ToString();
}
You have local variables multip_result1
, multip_result2
, multip_result3
which hide the fields with the same names, just remove them from the event handlers. So f.e. this:
double a, b, multip_result1;
becomes
double a, b;
otherwise you assign the calculated value to this local variable and the field remains 0.
If you want to assign to the field with the same name you could also use this.fieldName
. But i'd strongly advise against using the same name to avoid issues like this.