Search code examples
c#winformsuser-controls

Can't access parent form's button properties through user control form


I have parent form called MainBackground and a user control named LoginUI. LoginUI is docked into the MainBackground.

I need to change enability of a button (InfoButton) located in parent form to "true" when user clicks on the button "Log in" in the control form.

But I can't access the parent button's properties.

Control form's button clicking event code:

private void button1_Click(object sender, EventArgs e)
        {
            MainBackground.infoButton.Enabled = true;    
        }

I tried solving it with parent controls, but still it doesn't seem to work.

Thanks for any help!


Solution

  • You can't access MainBackground.infoButton from LoginUI because infoButton is not static.

    to solve this you could inject MainBackground trough a property like the example below

    public partial class LoginUI : UserControl
    {
        public MainBackground MainBackground { get; set; }  
        ...
    }
    

    in MainBackground you should initalize your LoginUI.MainBackground propery

    loginUI1.MainBackground = this;
    

    Make sure to make infoButton public by setting the modifiers property to public

    Now you can access MainBackground.loginUI1

    private void login_Click(object sender, EventArgs e)
    {
       MainBackground.InfoButton.Enabled = true;
    }