Search code examples
c#user-controls

How to change the properties of controls of a usercontrol at runtime in C#?


I am a novice to C#.

My application contains Main form and a few usercontrols. I want the usercontrol named "uc_MainMenu" to be displayed in the panel named "panel2" inside the Main form when I start running the applicaiton.

uc_MainMenu obj_uc_MainMenu = new uc_MainMenu();

private void frmMain_Load(object sender, EventArgs e)
{
     this.panel2.Controls.Add(obj_uc_MainMenu);
}

It works.

uc_MainMenu contains a few buttons: btnHeadmaster,btnTeacher,btnStudent,btnAttendance,btnExam and btnLogin. Each of those buttons' click will bring the corresponding predefined usercontrols.

Here is my question. I want to disable all the buttons except btnLogin when the form loads. How can I do that?

I tried this way but it didn't work.

foreach (Control ctrl in panel2.Controls)
 {
     if (ctrl.GetType() == typeof(Button))
         {
            ((Button)ctrl).Enabled = false;
         }
  }

I can change each button's enabled properties in the uc_MainMenu, but if so I will have to change them again whenever I switch the usercontrols. That's why I left their enabled property to true when I designed the usercontrols.


Solution

  • Create a property inside user control :

    public bool MyButtonEnabled
    {
        get
        {
            return anyButtonButNo_btLogin.Enabled;
        }
        set
        {
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl.GetType() == typeof(Button) && ((Button)ctrl).Name != "btLogin")
                {
                    ((Button)ctrl).Enabled = value;
                }
            }
        }
    }
    

    Now you can use this property anywhere that usercontrol used.

    uc_MainMenu obj_uc_MainMenu = new uc_MainMenu();
    
    private void frmMain_Load(object sender, EventArgs e)
    {
         this.panel2.Controls.Add(obj_uc_MainMenu);
    
         ///this property will access the button inside that user control
         obj_uc_MainMenu.MyButtonEnabled=false;
    }