Habilitar un botón desde otro formulario y cerrar el formulario

I have Form1 and Form2

Form1 I have a button that is disabled, but if I click on the menustrip on Form1 I go to Form2. On Form2 I log into a database. After I logged in successfully, I want Form2 to close and I want the button on Form1 to be enabled.

Aquí está mi código:

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");
    }
}

preguntado el 31 de julio de 12 a las 12:07

3 Respuestas

Open your second form using ShowDialog, then use the DialogResult returned by the ShowDialog Function to enable the Button in your first form when you close the second form

Respondido 31 Jul 12, 12:07

You are creating new instance of the Form1. Don't do that, instead you need to show the Form2 as dialog and set the dialog result as OK.

Como este

Formulario 1 -

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

or

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

And in the Form2, after successful login set the DialogResult as OK.

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

Respondido 31 Jul 12, 12:07

You should not create another anstances of Form1 and Form2. Instead, you shoud have a public property of Form1, so you can enable your button. like shown in the code below :

//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");
    }
}

And you set this MyMainForm when calling the Form2 from Form1. Like this :

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

PS : The access modifier of you button shoud be public.

Respondido 31 Jul 12, 12:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.