-1

I'm using two forms. In first Form1 I have a TextBox from which I send a value into a class Class1. Here is my Form1 Code:

Class1 ss = new Class1();
ss.name = textBox1.Text;

Here is My Class Code:

class Class1
{
    public string name;
}

But when I open another Form. Example Form2 and I'm trying to take the value from Class1 it returns null.

Here is my Form2 Code:

 Class ss = new Class();
 textBox2.Text = ss.name;

How can I use public string name for any Form I open?

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Dim
  • 97
  • 2
  • 9
  • 7
    Probably at your level you should use a static variable. If you don't know what a static variable is, stop what you're doing and go read up about it. In fact, you should stop everything you're doing, go get CLR Via C#, read it over the course of a day, and then come back to this. –  Feb 22 '17 at 13:28
  • Make that class static. https://msdn.microsoft.com/en-us/library/79b3xss3.aspx – Muhammad Saqlain Feb 22 '17 at 13:28
  • 1
    Possible duplicate of [C# - Winforms - Global Variables](http://stackoverflow.com/questions/1293926/c-sharp-winforms-global-variables) – Igor Feb 22 '17 at 13:29

2 Answers2

1

You're creating a new class which will have a new 'empty / null' name value by default. You need to either use the same class or make the name static.
Just to make this example work, the easy solution would be static but I don't think in the end that this is what you're going to want.

public static string name;
Michael Puckett II
  • 6,586
  • 5
  • 26
  • 46
  • " You need to either use the same class" He is using the same class, just not the same instance – Mong Zhu Feb 22 '17 at 13:32
  • 1
    Ok wise crack... You know exactly what I meant. Yes, you are correct, the same 'instance'. It should have been worked creating a new 'instance' ... use the same 'instance'. – Michael Puckett II Feb 24 '17 at 12:51
1

Your problem is that it is not the same instance in the 2 forms. In the second you create a new instance with an empty name variable

How can i use public string "name" for any Form i open?

if you only use it as a container to pass data then make the name variable static. That would mean that it exist only once! but you don't need an instance to access the variable!

class Class1
{
    public static string name;
}

Then you can pack it in Form1

Class1.name = textBox1.Text;

and unpack it in Form2:

textBox2.Text = Class.name;

But the preferable option would be to pass the variable Class1 ss that you feed with the textBox1.Text into the Form2 maybe via the constructor

Form2

public Form2(Class1 c)
{
     textBox2.Text = c.name;
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76