none
When to init controls in a Windows form, in the constructor or Form_Load? RRS feed

  • Question

  • Where is it best to init (simply assign values to the .Text of the controls), for example, edit boxes and lables in a WindowsForm?

    I've seen that I can do it in the constructor or in the Form_Load.

    I'd prefer to do it in the constructor, since otherwise don't need Form_Load, so, are there any disadvantages of doing it in the contructor?

    Here's an example, look at tbNumDirs.Text:

            // Constructor
            public CCrossSettingsForm(CCrossShader ShaderIn)
            {
                InitializeComponent();
                if (ShaderIn == null)
                {
                    MessageBox.Show("CCrossSettingsForm bad shader in");
                    return;
                }
    
                m_Shader = (CCrossShader)ShaderIn.Clone();
    
                //tbNumDirs.Text = string.Format("{0:0}", m_Shader.iNumDirections);
                //tbFirstAngle.Text = string.Format("{0:0.0}", m_Shader.FirstAngle);
            }
    
            private void CCrossSettingsForm_Load(object sender, EventArgs e)
            {
                tbNumDirs.Text = string.Format("{0:0}", m_Shader.iNumDirections);
                tbFirstAngle.Text = string.Format("{0:0.0}", m_Shader.FirstAngle);
            }
    
    
    I ask because in MFC C++ you must do it in the OnInitDialog and must not do it in the constructor of a CDialog. But it looks like in C# Windows Form you can do it in the constructor...


    http://www.ransen.com Cad and Graphics software


    • Changed type BonnieBMVP Saturday, August 26, 2017 2:35 PM question
    • Edited by Owen Ransen Sunday, August 27, 2017 6:21 AM added an example
    • Moved by CoolDadTx Monday, August 28, 2017 3:19 PM Winforms related
    Saturday, August 26, 2017 1:55 PM

Answers

  • Greetings Owen.

    In the case of the text of controls, you can set them in the constructor, but it must be after the call to InitializeComponent(). If you put those two lines in your example before the call to InitializeComponent(), you will get an exception because the controls won't have been instantiated yet.

    • Marked as answer by Owen Ransen Monday, August 28, 2017 4:55 PM
    Monday, August 28, 2017 6:39 AM
  • >> Well, you certainly don't want a MessageBox.Show() in your Constructor

    Why not? The error (in this case) would be serious and the program would not be able to continue.

    OK, sorry I missed the fact that you have ShaderIn as a constructor parameter. So, in this case, there's nothing wrong with setting it there in that constructor.  Sorry, that was my mistake.

    So, in this particular constructor (because it is not the parameter-less constructor), it should be OK to set the two TextBoxes there (where you have commented them out, go ahead and uncomment them) and then the code in the Load is not necessary.

    Sorry for the confusion. I've had a cold for the past few days, so I guess I'm missing things that are in plain sight ... at least that's my excuse for now.  ;0)

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by Owen Ransen Monday, August 28, 2017 7:23 PM
    Monday, August 28, 2017 6:35 PM

All replies

  • Where is it best to init, for example, edit boxes and lables in a WindowsForm?

    I've seen that I can do it in the constructor or in the Form_Load.

    I'd prefer to do it in the constructor, since otherwise don't need Form_Load, so, are there any disadvantages of doing it in the contructor?


    http://www.ransen.com Cad and Graphics software

    In writing the logic of the program, in fact, there is no so-called the best time, look at the needs of the time, in fact, as you have mentioned "you prefer to do this in the constructor" This is also true. And some small projects need to be generated quickly, we may not need to spend too much time to build on, of course, there are many considerations, such as performance problems, just as you just want to learn from the 10,000 information just want to put a piece of information You will not write all read out.

    If your question is replaced by "There is a project that has some needs, can some of the functions be written on the constructor?" This may let us to give more specific advice.

    Form {
    //It must be better to code here for
    bla...bla...bla
    }

    Back to your question,because this logic layer is too wide, this answer is the accumulation of experience. 



    Saturday, August 26, 2017 2:17 PM
  • That totally depends on what you mean by "init". A WinForm automatically generates the InitializeComponent() for you, and that should always be left in the constructor. You can initialize a few simple fields/properties in the constructor as well. But anything involving getting data to databind the controls should be done in the Form_Load. The reason mainly has to do with designing your Forms in Visual Studio, because the Designer runs the constructor of the Form ... and you don't need to have data when you're designing your Form visually. And, if any of that extra stuff in the constructor causes an exception, you won't be able to bring up your Form in the Designer.

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Saturday, August 26, 2017 2:33 PM
  • In my experience, I could give you what diferent between constructor or Form_Load.

    Code in the constructor runs immediately when you create the form, whether or not you ever display it. Code running in the Form.Load event is an event handler, so you can actually have code in other classes (which have subscribed to the form) run code there. Similarly, you can (from the form) use the Form.OnLoad method to run code.

    protected virtual void OnLoad(
    	EventArgs e
    )


    The form's Load event (and OnLoad overridable method, which is often a better choice in the form itself) runs after the form has been initialized. This often has advantages, since all of the form's controls have already been constructed, and more importantly, all of the form layout has occurred.

    Well simply put the constructor is called when the class is instantiated like all constructors, while the page load is called whenever a form is displayed for the first time.

    Personal experience in the development of a nearly 20 years of advice, hoping to help you. : )



    Saturday, August 26, 2017 2:33 PM
  • Actually there are three places, in the new constructor, the load event and the shown event, it all is dependent on what operations are being performed e.g. loading controls from a database or perhaps xml or a web data source to bind to controls. 

    If the process takes time and doing operations in one of the three areas it might be prudent to use a splash screen especially for the constructor and load events. 


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, August 26, 2017 9:48 PM
    Moderator
  • I've edited the original post to make my question more clear...

    http://www.ransen.com Cad and Graphics software

    Sunday, August 27, 2017 6:22 AM
  • That totally depends on what you mean by "init".

    Thanks, I've edited my original post to make it clearer...

    http://www.ransen.com Cad and Graphics software

    Sunday, August 27, 2017 6:22 AM
  • Here's a VB answer to the same question:

    When to INIT a form

    It suggests in the constructor is the best place.

    http://www.ransen.com Cad and Graphics software

    Sunday, August 27, 2017 6:24 AM
  • Well, you certainly don't want a MessageBox.Show() in your Constructor (as I said earlier, you could have trouble opening your Form in the Designer). Also, anything that could cause an exception should *not* be in the Constructor. We don't know what ShaderIn is, nor do we know what ShaderIn.Clone() does. If it's not possible that it will throw an exception, then you could leave it in the constructor. However, I still think that it's probably a bad habit to get into and you should really put that kind of code in the Form_Load.

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, August 27, 2017 2:29 PM
  • Hello Owen Ransen,

    >>since otherwise don't need Form_Load, so, are there any disadvantages of doing it in the contructor?

    Just remember constructor is called when the class is instantiated like all constructors, while the page load is called whenever a form is displayed for the first time.

    Let's explain base on the code, if you want to show other form from current form . You could do something like below.

     Form5 f5 = new Form5();
    
      f5.Show();

    The constructor will be called by the first statement , And the load event will be called by the second statement. If the load event have some complicated logic and code, It will delay the appearance of the window. So I think constructor is a good place to assign resources to object.

    Best regards,
    feih_7


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Edited by Fei Hu Monday, August 28, 2017 6:27 AM
    Monday, August 28, 2017 6:24 AM
  • Greetings Owen.

    In the case of the text of controls, you can set them in the constructor, but it must be after the call to InitializeComponent(). If you put those two lines in your example before the call to InitializeComponent(), you will get an exception because the controls won't have been instantiated yet.

    • Marked as answer by Owen Ransen Monday, August 28, 2017 4:55 PM
    Monday, August 28, 2017 6:39 AM
  • >> Well, you certainly don't want a MessageBox.Show() in your Constructor

    Why not? The error (in this case) would be serious and the program would not be able to continue.

    I have not had any problems in the designer doing this...


    http://www.ransen.com Cad and Graphics software

    Monday, August 28, 2017 4:57 PM
  • >> Well, you certainly don't want a MessageBox.Show() in your Constructor

    Why not? The error (in this case) would be serious and the program would not be able to continue.

    OK, sorry I missed the fact that you have ShaderIn as a constructor parameter. So, in this case, there's nothing wrong with setting it there in that constructor.  Sorry, that was my mistake.

    So, in this particular constructor (because it is not the parameter-less constructor), it should be OK to set the two TextBoxes there (where you have commented them out, go ahead and uncomment them) and then the code in the Load is not necessary.

    Sorry for the confusion. I've had a cold for the past few days, so I guess I'm missing things that are in plain sight ... at least that's my excuse for now.  ;0)

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by Owen Ransen Monday, August 28, 2017 7:23 PM
    Monday, August 28, 2017 6:35 PM