Search code examples
c#winforms

The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified


To load my ComboBox at the beginning I used the mine method LoadDataFromDB() in the InitializeComponent() method, but there is an warning says:

The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified

So where can I load my ComboBox?


Solution

  • Use form's constructor

    public Form1()
    {
        InitializeComponent();
        LoadDataFromDB();
    }
    

    Or (sometimes better) Form.Load event handler (it will be added automatically when you double-click form in designer):

    private void Form1_Load(object sender, EventArgs e)
    {
        LoadDataFromDB();
    }
    

    Another option is overriding OnLoad method of form.

    NOTE: You see this warning, because InitializeComponent is generated by designer, and it will be completely re-generated when you'll change something in designer (add some control, move or resize some control, change color etc). Thus all your changes to this method will gone.