c# - 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'
问题?
我的所有控件都已设置为公开。我正在阅读和阅读,但无法弄清楚,这让我现在很生气。我不期待一个现成的解决方案,只是一个很好的解释。
解决方案
您可以像这样在登录表单上引发一个事件:
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;
}
}
推荐阅读
- mysql - dpkg-deb: 错误: 'mysql-apt-config_0.8.14-1_all.deb' 不是 Debian 格式存档
- java - Android 应用程序在本机堆中消耗过多内存 - Android 分析器
- pandas - 如何在分类变量中获取各种类别组合并同时聚合它?
- docker - 在 Docker 中运行 Kong,Kong 在 Web 浏览器中不显示 GUI
- c# - 多个文本框输入和多个文本框通过数组输出
- ios - Flutter 在目标 Runner 上自动分配版本为 9.0 的平台 iOS,因为没有指定平台
- javascript - Safari preventDefault() 不适用于 AudioContext
- linux - Ansible grep 多个文件,然后将输出发送到邮件(使用了错误的库存)-已解决
- python - 如何在不使用类名的情况下从静态方法调用静态方法
- excel - VBA代码没有在excel中运行大量数据