Tuesday, April 5, 2016

Windows Form - Using user controls

To separate UI with minimize coding effort, solve smaller problem or reuse purpose, we usually use sub-form or user control. In this topic, I will introduce how to call multi User Controls from parent form. With this idea you can make design UI for many kind of simple apps to enterprise apps. Let's get started:
      1.     Create new project:
-          Create new project by select: File > New > Project…
-          Enter the project name and click OK
      2.       Add controls
-          In Toolbox, find MenuStrip control, then add to form.
-          Enter some StripMenuItem, look like:


-          Rename all StripMenuItem like: smiControl01, smiControl02, smiControl03
-          Then, in Toolbox, find Panel control, add to form. Set this panel Dock property is Fill or do like this:

-          I named this panel is pnlMain
      4.       Add UserControls
-          In Solution Explorer, right click on project name, select Add > New Item…
-          Select User Control, named it and click Add

-          Do the same for 3 User Controls
       5.       Show/Add UserControls to form
-          Now, let’s do some coding. In the backend code of the form, create add user control to panel function
private void AddUserControlToPanel(Control ctrl)
{
    //Clear all old control
    pnlMain.Controls.Clear();
    //Add the new control
    pnlMain.Controls.Add(ctrl);
    //Make control fill in the panel
    ctrl.Dock = DockStyle.Fill;
}
-          In each click event of StripMenuItem, call that function with parameter is the relevant control
private void smiControl01_Click(object sender, EventArgs e)
{
    AddUserControlToPanel(new MyControl01());
}
private void smiControl02_Click(object sender, EventArgs e)
{
    AddUserControlToPanel(new MyControl02());
}
private void smiControl03_Click(object sender, EventArgs e)
{
    AddUserControlToPanel(new MyControl03());
}
-          You can also can call a default control when load form by call function AddUserControlToPanel in form constructor
-          Note that, each user control can treat like a form, so you should do some design user controls before run check our result.
  

      6.       Resize form
-          You may wanna change the size of form when control added to make User Control appear fully
-          Edit the AddUserControlToPanel function
private void AddUserControlToPanel(Control ctrl)
{
    //Clear all old control
    pnlMain.Controls.Clear();
    //Add the new control
    pnlMain.Controls.Add(ctrl);
    //Make control fill in the panel
    //ctrl.Dock = DockStyle.Fill;
    //Change size form
    this.ClientSize = new Size(ctrl.Width, ctrl.Height + menuStrip1.Height);
}
-          Make controls are different size and color then run project 

Thank you for reading.

No comments:

Post a Comment