I am trying to add a code behind the add button my code is this:
class CalculateValues
{
private int _num1;
private int _num2;
public int Num1
{
get
{
return _num1;
}
set
{
_num1 = value;
}
}
public int Num2
{
get
{
return _num2;
}
set
{
_num2 = value;
}
}
public virtual int calculate()
{
return _num1 + _num2;
}
}
Here is the other code that has the button on it:
public partial class Form2 : Form
{
public Form2()
{
CalculateValues myAdd = new CalculateValues();
MulitplyValues Add = new MulitplyValues();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myadd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
But everytime it tell me 'myAdd' does not exist in the current context
I am not understanding why it is not working. I have even tried a few different ways.
This is a scope issue. You define
myAddinside the constructorForm2(), which means it’ll only be available in that scope: only the constructor can use it, after that it’s gone.If you want a variable to persist, move it to the class scope.
I recommend reading this article