locked
Form constructor priority

    Question

  • Seems I can actually do this:

    public partial class MainForm : Form
     {

    public MainForm()
    {
                trackBar_A.Value = 6;
    }

            private void trackBar_A_Scroll(object sender, EventArgs e)
    {
    ...
    }
    }

    How can this work if the constructor is operating on something that hasn't yet been constructed?

    Dirk
    Tuesday, January 29, 2008 3:19 AM

Answers

  • I'd do it on a handler of the Load event...
    If you're using VS, if you double click the form in the designer it creates a handler of the Load event called FormName_Load.
    Tuesday, January 29, 2008 2:20 PM

All replies

  • If you don't initialize trackBar_A it will throw a NullPointerException at runtime.
    Tuesday, January 29, 2008 3:34 AM
  • Sorry.  Your post is not clear to me.  What do you mean by your can "do this"?  And what has not been constructed--the form or the trackBar?  You are also not revealing all of the code in your class MainForm.  The "partial" keyword means that there may be more of your MainForm in another file--MainForm.Designer.cs perhaps?

    Tuesday, January 29, 2008 3:46 AM
  •  jrboddie wrote:

    Sorry.  Your post is not clear to me.  What do you mean by your can "do this"?  And what has not been constructed--the form or the trackBar?  You are also not revealing all of the code in your class MainForm.  The "partial" keyword means that there may be more of your MainForm in another file--MainForm.Designer.cs perhaps?



    Loads of other stuff, including 32 trackbars.
    What I was curious about is how initialising the trackbars (and other stuff on the form) works when its in the form constructor. Does the form get 'constructed' with all the trackbars etc, then initialised from the form constructor?

    Dirk
    Tuesday, January 29, 2008 12:59 PM
  • Have you a file called XXX.designer.cs?
    This is a partial class, and there will be some initialization code, that creates the controls.

    Tuesday, January 29, 2008 1:06 PM
  •  penyaskito wrote:
    Have you a file called XXX.designer.cs?
    This is a partial class, and there will be some initialization code, that creates the controls.



    Yes - it contains all the automatically generated code from the form designer tool.
    Question is, when I run the form I want to load trackbar values etc automatically from a file. Where do I put that bit of code?

    Dirk
    Tuesday, January 29, 2008 1:37 PM
  • I'd do it on a handler of the Load event...
    If you're using VS, if you double click the form in the designer it creates a handler of the Load event called FormName_Load.
    Tuesday, January 29, 2008 2:20 PM
  •  penyaskito wrote:
    I'd do it on a handler of the Load event...
    If you're using VS, if you double click the form in the designer it creates a handler of the Load event called FormName_Load.


    Yes! That's it!

    Thanks
    Dirk
    Tuesday, January 29, 2008 2:32 PM