在我的程序中,我有两种形式。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'
问题?
我所有的控件都已经设置为public.我看了又看,想不通,现在快把我逼疯了,我不期望有一个现成的解决方案,只希望有一个好的解释。
你可以像这样在你的登录表单中引发一个事件。
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;
}
}
由于Form1不是静态类,所以你应该创建这个类的对象,然后设置可见性为true,如
Form1 formobj=new Form1();
formobj.groupBox2.Visible = true;