How to change component attributes between Forms?

Asked

Viewed 869 times

0

I have an application in C# with a parent Form (FRM_PRINCIPAL) that contains a button (BTN_ACT) that calls a Child Form (Form2), which in turn contains a button (BTN_REG) containing some functions, among which one would make BTN_ACT invisible (BTN_ACT.Visible=False;). How would I do that? Simply put: Basically make the first Form button invisible via a second Form button.

1 answer

2


In your FRM_PRINCIPAL, you need to create a public method to set the visibility of your button.

public void AlteraVisibilidadeBtnAct(bool visivel)
{
    this.BTN_ACT.Visible = visivel;
}

In your BTN_REG button click method, you call the method created above as follows, if Form2 is a child of your FRM_PRINCIPAL. One form is the child of the other when the Mdiparent property is set for the child.

private void BTN_REG_Click(object sender, System.EventArgs e)
{
    ParentForm.AlteraVisibilidadeBtnAct(false);
}

If Form2 is not FRM_PRINCIPAL child, you must add FRM_PRINCIPAL to the Form2 constructor, and then access it in the click event.

private FRM_PRINCIPAL frmPrincipal;

public Form2(FRM_PRINCIPAL frmPrincipal)
{
    this.frmPrincipal = frmPrincipal;
}

private void BTN_REG_Click(object sender, System.EventArgs e)
{
    frmPrincipal.AlteraVisibilidadeBtnAct(false);
}
  • Thank you Bernardo! The code I am compiling that apparently fits my case is what you said "If Form2 is not the child of FRM_PRINCIPAL...". However I am receiving "An unhandled Exception of type 'System.Nullreferenceexception' occurred in...". This error is happening on the frmPrincipal.Alteravisibilidadebtnact(false); in my Form2.

  • You need to pass FRM_PRINCIPAL as the parameter for Form2, in the line where Form2 is created. The code would look something like this: Form2 form2 = new Form2(this), if you are creating Form2 within the FRM_PRINCIPAL class.

  • Thank you very much, it worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.