I am having a bit of trouble passing variable between forms. I have created a button array and want to pass the button text to the next form. But this is just returning a Null value
In the first form
private string staffmem;
public string Staffmem
{
get
{
return staffmem;
}
}
public void ClickButton(Object sender, EventArgs e)
{
Button btn = (Button)sender;
staffmem = btn.Text;
MessageBox.Show("Welcome " + staffmem);
MainScreen ms = new MainScreen();
ms.Show();
}
and then in the second form
private void MainScreen_Load(object sender, EventArgs e)
{
Form1 f1 = new Form1();
staffmem = f1.Staffmem;
Any help would be much appreciated. Thanks in advance
You are creating new forms in both ends of the communication: when the button is clicked and when you want to retrieve the text — this results in accessing the
Staffmemfield on a newly created object, which field has not been set to anything, hence the returnednullvalue.In order to be able to retrieve the text, you need to have the same
Form1object toMainScreenwhen it is created:where
form1is the actualForm1object, and store it inMainScreenas a member variableThen access
Staffmemon that object on the stored member variable:Note: depending on your need, you might not want to create a new
MainScreenfrom every time the button is clicked either. In that case (if you already have a createdMainScreenthat you want to communicate with), you need to pass theMainScreenobject to theForm1object as well, when theForm1object is created (following the above outlined techniqe)