user controls constructors

  • Thread starter Thread starter Alejandro González
  • Start date Start date
A

Alejandro González

Hi.
I have this problem.
I create a user control with a constructor with several parameters.
I also add the default constructor so I can add this control in desing time
to a form.

Why this isn't working?
(default constructor was called in InitializeComponent())
private void Form1_Load(object sender, System.EventArgs e){
this.userControl1 = new UserControl("use this parameter");
}

after this call to the alt constructor I can debug and check that everthing
is ok, but the form still shows the control with old values.

thanks
 
the field "this.userControl1" is one thing; however, this isn't what gets
shown; the Form only knows about the items in its Controls collection; what
I would do is:

if(userControl1!=null) Controls.Remove(userControl1); // ditch the old one
userControl1 = new ... // blah
Controls.Add(userControl1);

obviously you need to tweak this if the control isn't directly on the form,
but is actually on a sub-control (panel, etc). Note that it also won't
preserve any width, height, position, etc (or anything else) that was set in
the designer if you re-initialise it *after* the designer-generated code.

Marc
 
I meant to add: all of this should prompt you to at least consider if you
couldn't use some kind of post-initialisation, e.g. a property setter, or an
Initialise(someParam) method that you could call once it exists, while
letting the designer etc work normally. Of course this isn't an issue if you
don't use the IDE to layout your forms.

Marc
 
Alejandro González said:
I have this problem.
I create a user control with a constructor with several parameters.
I also add the default constructor so I can add this control in desing time
to a form.

Why this isn't working?
(default constructor was called in InitializeComponent())
private void Form1_Load(object sender, System.EventArgs e){
this.userControl1 = new UserControl("use this parameter");
}

after this call to the alt constructor I can debug and check that everthing
is ok, but the form still shows the control with old values.

That's because presumably the control created with the default
parameter has been added to the Controls collection, but nothing's
added the new one you've just created.

Bear in mind that if you just create a new one, it won't have any of
the settings you put into the designer (size, location etc).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top