Search code examples
c#winformseventsuser-controls

Using form elements to interact with UserControls


I have a button on a user control, that by default is not enabled. When an event happens on the Form, I want it to be able to enable the button. I have set a button on the main form to test this, and it appears to set the UC button to enabled, but it doesn't appear enabled in the application.

public partial class Form1 : Form
{

    public Login ucLogin = new Login();

    private void button1_Click(object sender, EventArgs e)
    {
        if (ucLogin.loginEnabled)
        {
            MessageBox.Show("True");
        }
        else
        {
            MessageBox.Show("False");
            ucLogin.loginEnabled = true;
        }


    }
}

Form.cs

And in the usercontrol for the login form:

public partial class Login : UserControl
{
    public bool loginEnabled
    {
        get { return ucBtn.Enabled; }
        set { ucBtn.Enabled = value; }
    }
}

What's strange is if I click the Form button1, it will say "False", if I click it again, it will say "True", indicating that it does change the value of the UC button, but on the application, it remains disabled.


Solution

  • The Login user control that you see on the form is likely not the instance you are setting loginEnabled property on.