C# 窗体。启用另一个 class 的控制

C# WinForms. Enable control from another class

在我的程序中,我有两种形式:public partial class Form1 : Form,

和登录表格:public partial class Login : Form。都在同一个 namespace

登录 window 在主 window 上单击登录按钮时打开:

public partial class Form1 : Form
{
    private void LoginToolStripMenuItem_Click(object sender, EventArgs e) //Login button event
    {
        LoginWindow = new Login();
        LoginWindow.ShowDialog();
        LogOutToolStripMenuItem.Enabled = true;
    }
}

输入密码后,我想在主屏幕上为用户启用其他控件。

groupBox2默认是不可见的,现在我想让它可见:

public partial class Login : Form
{
    public Login()
    {
        InitializeComponent();
    }

    public void button1_Click(object sender, EventArgs e) //Confirm click event
    {
        if (textBox1.Text == Form1.password)  //Here, no trouble accessing a string from the main screen
        {
            Form1.groupBox2.Visible = true; //********** Here is my problem **********
            Form1.LoginWindow.Close();
        }
        else
        {
            textBox1.Text = "Incorrect password";
            textBox1.SelectAll();
        }
    }
}

如何克服 "An object reference is required for the non-static field, method or property 'Form1.groupBox2' 问题?

我的所有控件都已设置为 public。 我正在阅读和阅读,但无法弄清楚,这让我发疯了。 我不期待现成的解决方案,只是一个很好的解释。

因为 Form1 不是静态的 class ,所以你应该创建这个 class 的对象然后将可见设置为 true 就像

Form1 formobj=new Form1();
formobj.groupBox2.Visible = true;

您可以像这样在您的登录表单上发起一个事件:

public partial class Login : Form
{
  public EventHandler OnPasswordDone; // declare a event handler

  public Login()
  {
      InitializeComponent();
  }

  public void button1_Click(object sender, EventArgs e) 
  {
      if (textBox1.Text == Form1.password)  
      {
          // raise the event to notify main form
          OnPasswordDone(this, new EventArgs());
      }
      else
      {
          textBox1.Text = "Incorrect password";
          textBox1.SelectAll();
      }
  }
}

而在你的主窗体中:

public partial class Form1 : Form
{
    private void LoginToolStripMenuItem_Click(object sender, EventArgs e) //Login button event
    {
        LoginWindow = new Login();
        LoginWindow.OnPasswordDone += Login_PasswordDone; // regist your event here
        LoginWindow.ShowDialog();
        LogOutToolStripMenuItem.Enabled = true;
    }

    private void Login_PasswordDone(object sender, EventArgs e)
    {
        //Do what you need to do here like:
        groupBox2.Visible = true;
    }
}