I understand that you defined the variableA
like below:
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class First_Form : Form
{
public ushort variableA = 0;
public First_Form()
{
InitializeComponent();
}
}
}
then I declare in another class in this new form:
First_Form My_variableA= new First_Form();
Please note that new First_Form()
will create new instance of First_Form class in which the variable variableA
is initialized with value of 0.
That's why you observed:
the public variable value on button click does not get modified???
To resolve the issue, I suggest that you change the variableA
to static as shown below:
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class First_Form : Form
{
public static ushort variableA = 0;
public First_Form()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
variableA = 1;
var new_Form = new New_Form();
new_Form.Show();
}
private void button2_Click(object sender, System.EventArgs e)
{
variableA = 2;
var new_Form = new New_Form();
new_Form.Show();
}
}
}
and refer the variableA
in new Form as follows:
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class New_Form : Form
{
public New_Form()
{
InitializeComponent();
this.label1.Text = "First_Form.variableA: " + First_Form.variableA;
}
}
}
The result is: