Form1.cs
public String Return_inf()
{
names = U_name.Text;
return names;
}
我尝试将其存储在另一个类字符串变量中,如:
public string CheckLogin()
{
Form1 f = new Form1();
string name=f.Return_inf();
}
但变量是空的......
答案 0 :(得分:1)
您的变量名称为空的原因是您在CheckLogin()方法中创建了一个全新的Form1对象,而不是使用已存在的Form1对象。
您可以让您的课程彼此引用。
以下是一个示例,您可以尝试让表单互相引用
Form1类:
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课程:
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
}
}
还有其他方法可以做到这一点,但IMO这将是两种表单之间共享数据的基础。
答案 1 :(得分:0)
你可以通过定义像这样的静态类
来做到这一点static class GlobalClass
{
private static string U_name= "";
public static string U_name
{
get { return U_name; }
set { U_name= value; }
}
}
您可以按照以下方式使用
GlobalClass.U_name="any thing";
然后像这样回忆起它
string name=GlobalClass.U_name;