Reputation: 11
Form1.cs
public String Return_inf()
{
names = U_name.Text;
return names;
}
And i try to store it in another class string variable like :
public string CheckLogin()
{
Form1 f = new Form1();
string name=f.Return_inf();
}
But the variable is empty ....
Upvotes: 0
Views: 1238
Reputation: 9041
The reason your variable name is empty is because you are creating a brand new Form1 object in your CheckLogin() method, instead of using an already existing Form1 object.
You could have your classes have references to one another.
Here is one example you could try by having the forms have references to one another
Form1 class:
public class Form1 : Form
{
// Class variable to have a reference to Form2
private Form2 form2;
// Constructor
public Form1()
{
// InitializeComponent is a default method created for you to intialize all the controls on your form.
InitializeComponent();
form2 = new Form2(this);
}
public String Return_inf()
{
names = U_name.Text;
return names;
}
}
Form2 class:
public class Form2 : Form
{
// Class variable to have a reference back to Form1
private Form1 form1;
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
}
public string CheckLogin()
{
// There is no need to create a Form1 object here in the method, because this class already knows about Form1 from the constructor
string name=form1.Return_inf();
// Use name how you would like
}
}
There are other ways of doing this, but IMO this would be the basics of sharing data between two forms.
Upvotes: 1
Reputation: 61
you can do it by defining static class like this
static class GlobalClass
{
private static string U_name= "";
public static string U_name
{
get { return U_name; }
set { U_name= value; }
}
}
and you can use it as follow
GlobalClass.U_name="any thing";
and then recall it like this
string name=GlobalClass.U_name;
Upvotes: 0