繁体   English   中英

启用另一个表单中的按钮并关闭该表单

[英]Enabling a button from another form and closing the form

我有Form1和Form2

Form1我有一个禁用的按钮,但是如果我单击Form1上的菜单栏,则会转到Form2。 在Form2上,我登录到数据库。 成功登录后,我希望关闭Form2,并且希望启用Form1上的按钮。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection connection = new SqlConnection(@"...");
    SqlCommand command = new SqlCommand("SELECT * FROM UserT WHERE UserName ='" + 
        textBox1.Text + "' AND password ='" + 
        textBox2.Text + "'", 
        connection);

    connection.Open();
    SqlDataReader reader = null;
    reader = command.ExecuteReader();
    if (reader.Read())
    {
        MessageBox.Show("Welcome " + reader["UserName"].ToString());
        Form1 lfm = new Form1();
        lfm.button1.Enabled = true;
        Form2 fm = new Form2();
        fm.Close();
    }
    else
    {
        MessageBox.Show("Username and password " + 
            textBox1.Text + "does not exist");
    }
}

使用ShowDialog打开第二个窗体,然后在关闭第二个窗体时使用ShowDialog函数返回的DialogResult在第一个窗体中启用Button

您正在创建Form1的新实例。 不要这样做,而是需要将Form2显示为对话框,并将对话框结果设置为OK。

像这样

表格1-

Button1_Click()
{
Form2 frm2 = new Form2();
if(frm2.ShowDialog() == DialogResult.OK)
{
button1.Enabled = true;
}
}

要么

button1.Enabled = form2.ShowDialog() == DialogResult.OK;

在Form2中,成功登录后,将DialogResult设置为OK。

if(reader.Read())
{
DialogResult = DialogResult.OK;
Close(); //It may not required.
}

您不应创建Form1和Form2的另一个实例。 相反,您应该拥有Form1的公共属性,因此可以启用按钮。 如下面的代码所示:

//Form 2
public Form1 MyMainForm {get; set;}

private void button1_Click(object sender, EventArgs e)
{
    //Your code ...

    if (reader.Read())
    {
        MessageBox.Show("Welcome " + reader["UserName"].ToString());

        MyMainForm.button1.Enabled = true;

        //If you are already id Form2
        this.Close();
    }
    else
    {
        MessageBox.Show("Username and password " + 
            textBox1.Text + "does not exist");
    }
}

并且当您从Form1调用Form2时设置此MyMainForm。 像这样 :

Form2 f = new Form2() {MyMainForm = this};

PS:您按钮的访问修饰符应该是公开的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM