首页 > 解决方案 > C# WinForms。启用另一个类的控制

问题描述

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

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

单击主窗口上的登录按钮时会打开登录窗口:

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'问题?

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

标签: c#winformsclasscontrols

解决方案


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

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();
      }
  }
}

在你的主要形式中:</p>

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;
    }
}

推荐阅读