禁用其他表单中的控件

时间:2015-05-19 09:32:05

标签: c# winforms

我有两种形式。一个是MainForm,它是MDI父级,并且在MainForm加载时具有设置为enabled = false的ToolStripFile,另一个形式是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();
        }
    }

1 个答案:

答案 0 :(得分:0)

您正在创建主表单的新实例。实际上,您需要使用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;
        }