从另一个窗体禁用控件

本文关键字:控件 窗体 另一个 | 更新日期: 2023-09-27 17:49:56

我有两个表单。一个是MainForm,这是一个MDI父,并有一个ToolStripFile设置为enabled = false在MainForm加载,另一个形式是form2,这是一个MDI的孩子,并作为我的登录表单。如果登录成功,ToolStripFile应为"enabled = true"。我有这个代码,但它不起作用:

        private void btnLogin_Click(object sender, EventArgs e)
    {
        MainForm mf = new MainForm();
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "SELECT * FROM Employees WHERE Username = @Username AND Passcode = @Passcode";
            command.Parameters.AddWithValue("@Username", txtUsername.Text);
            command.Parameters.AddWithValue("@Passcode", txtPassword.Text);
            OleDbDataReader reader = command.ExecuteReader();
            int count = 0;
            while (reader.Read())
            {
                count = count + 1;
            }
            if (count == 1)
            {
                Employees emp = new Employees();
                //emp.MdiParent = this.MdiParent;
                //emp.Show();
                mf.ToolStripFile.enabled = true;
                this.Dispose();
            }
            if (count > 1)
            {
                MessageBox.Show("There is a duplicate in username and password.");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("ERROR: " + ex, "LOGIN");
        }
        finally
        {
            connection.Close();
        }
    }

从另一个窗体禁用控件

您正在创建主表单的新实例。您实际上需要使用MDIParent属性使用当前表单的实例。

你可以在父窗体中使用这样的内容:

        public bool EnableButton
        {
            set
            {
                button1.Enabled = value;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            MDIChild child = new MDIChild();
            child.MdiParent = this;
            child.Show();
        }

在子窗体中,您可以这样做:

        private void button1_Click(object sender, EventArgs e)
        {
            // if successful
            (MdiParent as MDIParent).EnableButton = true;
        }