c# – How to move the creation of the form into a separate class?

Question:

How to move the creation of the form into a separate class and access it normally?

public void LoadBtn_Click(object sender, EventArgs e)
{
    Form form = new Form();
    form.Show();

    form.Controls.Add(listBox1);
    listBox1.Size = new System.Drawing.Size(200, 100);
    listBox1.Location = new System.Drawing.Point(10, 10);
    listBox1.DisplayMember = "Title";
    listBox1.ValueMember = "Path";
    listBox1.MultiColumn = true;
    listBox1.SelectionMode = SelectionMode.MultiExtended;
   
    butReset.Text = "Сбросить настройки";
    butReset.Location = new Point(140, 160);
    form.Controls.Add(butReset);

    butLoad.Text = "Принять";
    butLoad.Location = new Point(30, 160);
}

Now a lot of code hangs on the button (Creating a form as well). The point is that this code needs to be used in many different places. I would like to be able to quickly integrate the form creation code into other projects and be able to scale this code. Now it looks terrible (in my opinion), but I don’t know how to endure it.

Answer:

As an option like this

public void LoadBtn_Click(object sender, EventArgs e)
{
    Form form = new MyCustomForm();
    form.Show();

}

you have a prepared form and you create it.

or another option.

If the form involves the creation of dynamically, then I recommend creating a factory. Which will generate forms for you

class FormFactory {

   public static Form createForm(yourParams) {
    // создаёте форму на основе параметров 
    Form form = new Form();
   
    form.Controls.Add(listBox1);
    listBox1.Size = new System.Drawing.Size(200, 100);
    listBox1.Location = new System.Drawing.Point(10, 10);
    listBox1.DisplayMember = "Title";
    listBox1.ValueMember = "Path";
    listBox1.MultiColumn = true;
    listBox1.SelectionMode = SelectionMode.MultiExtended;
   
    butReset.Text = "Сбросить настройки";
    butReset.Location = new Point(140, 160);
    form.Controls.Add(butReset);

    butLoad.Text = "Принять";
    butLoad.Location = new Point(30, 160);

    return form;

   }

}



public void LoadBtn_Click(object sender, EventArgs e)
{
    // подготавливаете параметры формы 
    ....
    Form form = FormFactory.createForm(yourParams);

    form.Show();    
}
Scroll to Top