-3

I've been trying to get this working. I'm sure I've written in correctely

Form 1

private string _temp;
public string Temp
{
    get { return _temp; }
    set { _temp = value; }
}
private void button1_Click(object sender, EventArgs e)
{
    _temp = "test";
}

Form 2

private void button1_Click(object sender, EventArgs e)
{
    Form1 main = new Form1();
    MessageBox.Show(main.Temp);
}
MAV
  • 6,967
  • 4
  • 33
  • 47
Alfie McNarutoad
  • 368
  • 1
  • 11
  • 20
  • What's the problem? You haven't described any issues with this code. – ryanyuyu Feb 04 '15 at 19:27
  • I'm trying to get the value of Temp from Form 1 to Form 2 – Alfie McNarutoad Feb 04 '15 at 19:28
  • possible duplicate of [Communicate between two windows forms](http://stackoverflow.com/questions/1665533/) – Dour High Arch Feb 04 '15 at 19:29
  • I tried checking if there are any values for "main.Temp" but it just said it's null – Alfie McNarutoad Feb 04 '15 at 19:29
  • you create a new instance of the form and then pull the value from the property - by default, it is null.This is expected. Why are you creating an instance of the form? Why not hold it in a global private variable and access it to then have the same instance you are pulling the data for or pass the variable value to the next form? – Ahmed ilyas Feb 04 '15 at 19:30
  • Yeah, and until you click Form1 main's button (and trigger that event handler), `main.temp` will be a default null. – ryanyuyu Feb 04 '15 at 19:32
  • [C# Basics Tutorial - Encapsulation](http://www.tutorialspoint.com/csharp/csharp_encapsulation.htm) I'd suggest reading and understanding the difference especially between `private && public` – MethodMan Feb 04 '15 at 19:38

1 Answers1

0

You have to get the reference to the Form1 instance via the sender parameter (assuming that Form2's button1_Click handler is attached to a button on Form1):

//Form2
private void button1_Click(object sender, EventArgs e)
{
    Button button = (Button) sender;
    Form1 main = (Form1) button.FindForm();
    MessageBox.Show(main.Temp);
}
Mark Cidade
  • 96,194
  • 31
  • 221
  • 232