首页 > 解决方案 > 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.

标签: c#winforms

解决方案


不要创建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);
    }
}

推荐阅读