calling the constructor of an usercontrol

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

Well, the problem is clear: How to call a constructor of a programmaticaly
loaded user control?

The LoadControl function obviously won't do it. And using this:


<%@ Register TagPrefix="uc1" TagName="newcontrol" Src="newcontrol.ascx" %>

code behind:



Panel1.Controls.Add(new newcontrol("abc"));

newcontrol.ascx (constructor code):



public newcontrol(string _text)

{

Label1.Text = _text;

}


Will give me this failure on runtime:

Compilerfailure: CS1501: No overload for the method 'newcontrol' requires
'0' arguments

Line 31: private static bool __initialized = false;
Line 32:
Line 33: public newcontrol_ascx() {
Line 34: if ((ASP.newcontrol_ascx.__initialized == false)) {
Line 35: ASP.newcontrol_ascx.__initialized = true;


Note: I'm not using an English .net framework, the above compiler failure
message was originaly in German, it's just my translation of the original
German Text. The same original text in English might be different.
 
The LoadControl function obviously won't do it.

Obviously, you're wrong. This is indeed how you load a user control
programmatically.

Of course, loading it doesn't add it to the Page, or whatever Control you
want to host it in. You have to do that as well.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Big things are made up of
lots of little things.

"the friendly display name"
 
..net doesn't support usercontrols with contructor args. move them to a
method you call after contruction.

-- bruce (sqlwork.com)


"the friendly display name"
 
The LoadControl method creates the instance. What do you need to call the
Constructor for?

The Constructor method you posted sets the text of a Label. Yes, I know, the
Label is not accessible. But you can make it accessible:

public string Label1Text
{
get { return Label1.Text; }
set { Label1.Text = value; }
}

UserControls are not designed to be instantiated by calling the Constructor.
They are made to be loaded declaratively (via inserting a tag in a Template)
or programmatically (using the LoadControl method). This is because they are
Templated Controls. If you want to create a Control that you can pass data
to in the Constructor, create a custom Server Control.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Big things are made up of
lots of little things.

"the friendly display name"
 
Back
Top