c# - C# class string used on a another Form
问题描述
i have a little problem on my form Login when i Login, i want send my username on the string username in my class functions.
And when my Main Form is loaded i want this class functions get the username from my form login with my username
i have try something like this:
My form login:
public Functions FUNCTIONS = new Functions(); //for my class Functions
FUNCTIONS.Username = "Username123";
My class Functions:
public class Functions
{
public string Username = ""; //empty
}
and my Main form after login
public Functions FUNCTIONS = new FUNCTIONS();
private void Main_Load(object sender, EventArgs e)
{
MessageBox.Show("Welcome "+ FUNCTIONS.Username " to my application.");
}
When my Main Form is loaded it's don't show the username string it's keep this empty, thanks for your time and your help for fix my problem.
解决方案
不要创建new
第二次,new
创建另一个Functions
实例。将现有的传递给主窗体并将其分配给主窗体中的字段。
public partial class LoginForm : Form
{
private Functions functions = new Functions();
public LoginForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
functions.Username = "Username123";
new MainForm.Show(functions);
this.Close();
}
}
public partial class MainForm : Form
{
private Functions functions;
public MainForm()
{
InitializeComponent();
}
public MainForm(Functions f) : this()
{
functions = f;
}
private void MainForm_Load(object sender, EventArgs e)
{
MessageBox.Show(functions.Username);
}
}
推荐阅读
- spring-boot - 数据表加载太慢
- autodesk-forge - 使用设计自动化 API 将 Revit 打印到 PDF - 不允许打印机设置、任何其他解决方法或解决方案
- android - JSONObject Azure 函数
- reactjs - 如何将 React 代码转换为 ClojureScript 代码?
- python - 不能声明双数组?
- javascript - 如何将请求 ID 值传递给模态?
- angular - Angular 7 Service 是未定义的异常
- excel - 修改通过 VBA IDE 创建的子和函数体的任何可能性
- swift - 结构作为具有完成功能的函数中的参数 - Swift
- elasticsearch - Elasticsearch 什么是网站搜索的最佳查询