LoadControl vs Construct ASP.Net Control - asp.net

I have a question why we can only add dynamic control using LoadControl.
For example:
public partial class wucReportParam : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
wucDate() ctrl = new wucDate();
pnl.Controls.Add(ctrl);
}
}
When in the page_load method of wucDate, the child control of wucDate is null but when i use the following method:
public partial class wucReportParam : System.Web.UI.UserControl
{
public Report Report;
protected void Page_Load(object sender, EventArgs e)
{
ctrl = (wucDate)LoadControl(#"Reports\wucDate.ascx");
pnl.Controls.Add(ctrl);
}
}
In the page_load method of wucDate, the child control of wucDate is not null.
Is anyone could explain to me why asp .net don't create any child control of wucDate when i using contructor ??? Thank you

When dynamically loading a user control, it is important to ensure that the standard ASP.NET page event pipeline is initiated and progresses normally. When you use the new operator to create an instance of a user control, that user control is not properly added to ASP.NET's event system. If the events (Init, Load, PreRender, etc.) to not fire, then your control will never function properly. That is why it is necessary to use LoadControl, as that will make sure that the instance of your user control is created properly and attached to ASP.NET.

Apparently, using LoadControl with typeof (or GetType) has the same problem as using 'new' where the child controls are not initialized. Using LoadControl with a string to the ASCX file works.
Does not initialize child controls.
LoadControl(typeof(MyReport), null);
Works!
LoadControl("Report.ascx");

The initialization of the controls inside a User Control is driven by the ASCX file. Using only "new SomeControl" will not cause this initialization to run, and even if it did, all the design (markup) in the ascx file would be lost.
Remember that the class "wucDate" is only the base class which the full user control inherits from. It's not the same class as you'll get when using LoadControl("wucDate.ascx").
And to be honest, LoadControl has not much, if anything, to do with the page life cycle. That part is handled when you add the control to the container's Controls collection.

As I recall, it pertains to how ASP.NET constructs page components at run time. In ASP.NET although your pages have a class which is defined in your code-behind file, their types don't truly exist until run time. Like a page, although you have a control defined the wucDate type isn't created until it is included at run time. For this reason, the control must be loaded with LoadControl in order to both initialize the type and properly run in through the page life cycle.
This is to the best of my memory so if I'm incorrect here please let me know.

Related

Using Ajax on a webApp

I'm working on an application and I would like to use Ajax to partially render part of web page instead of full post back. So I use scriptManager and updatepanel but I have an error in JS sys is not defined. I took a look in generated JS code and it seems that no Ajax client side framework has been loaded by scriptmanager, no reference at scriptressource.
I created a website by using vs2010 template to test ajax and all works fine but in web.config I don't found any difference. Is it a known problem?
Solution:
After comment and uncomment different part of my code i found that is my objectdatasource which cause the problem... ObjectDataSource use function instance to retrieve business object but since i use class properties as argument of my "select" objectdatasource function i need to define current instance of my page as object instance (1) but when work is finished is also disposed by objectdatasource .... :) i stop disposing process by using event "ObjectDisposing" (2) ...
(1)
protected void OdsRecordObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = this;
}
(2)
protected void OdsRecordObjectDisposing(object sender, ObjectDataSourceDisposingEventArgs e)
{
e.Cancel = true;
}
bye !

Converting ASP.Net Web Form to User Control OnPreInit event

I'm in the process of converting an ASP.Net webform into a User control and there an event that now says
no suitable method found to override
the event code causing the compile error
protected override void OnPreInit(EventArgs e)
{
//do some stuff
base.OnPreInit(e);
}
Is there any equivalent for a user control?
The OnInit override is available. The User Control Lifecycle on MSDN should help you in determining which event to correctly override. In any case what are you trying to achieve?
No. You'll have to use Init. I cannot think of anything I've ever done in PreInit that couldn't be done in Init just as well.
http://msdn.microsoft.com/en-us/library/system.web.ui.usercontrol_events.aspx

Accessing user controls’s constituent controls from a hosting web page

I’ve read that user control’s constituent controls can be accessed only by user control and thus web page that hosts this user control cannot receive the events, call methods or set properties of these contained controls.
But I’m not sure the above claim is true, since I was able to access ( from hosting web page ) ClickButton.Click event ( assume WebUserControl1 contains ClickButton control ):
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button ClickButton = (Button)WebUserControl1.Controls[0];
ClickButton.Click += someClickHandler;
}
thanx
The entire page is a tree of controls. You can "browse" through this tree regardless of the parent of that control. For example from inside a user control you could go down to the parent, which could be another control, then further down to the page, then to the master page, and so on.
So yes, you are correct, it's not hidden to the point you can't access it, but it's not published either. In a similar way using reflection you could call private methods that you couldn't otherwise. Using certain tools you could access and change code that's already compiled; so nothing is really out of reach.
These boundaries are set and used to minimize complexity, not as an absolute wall that cannot be crossed.
You can expose the user control's properties (i.e. settings), controls, and events publicly which means you don't have to find the control within the usercontrol.

ASP.NET 2.0 - Parent Page Class not accessible from custom control

1) I've page class
public partial class MyDelivery : System.Web.UI.Page
2) ASCX is in different subfolder
public partial class MyControls_Hello_Bye : System.Web.UI.UserControl
I am unable to access #1 parent page class from control
This problem annoyed me for quite a while. I don't think my solution is perfect, but it sure helps my junior developers in coding. We have a base user control that all user controls inherit and we (like you) we have a base page class that all pages must inherit (team rule). In the user control is a property called ParentForm which is strongly typed to the specific page type that will contain it (the page baseclass if that is variable or unknown at the time).
During the load event of the page, we manually set the Parentform Property of all user controls (we do this in our master page for all master page level controls as well).
protected Page_Load(object sender, System.EventArgs e)
{
this.myControl.ParentForm = this;
this.myControl2.ParentForm = this;
}
This provides immediate access from any user control back to the page and any of its exposed methods. It also provides a standardized (within our team) method of allowing controls to communicate between themselves through an interface in the ParentForm.
Our standard is to perform this assignment manually. For me this was a personnel consideration to make sure developers are aware of the controls they are adding (not setting the ParentForm will cause null reference exceptions if you attempt to access it obviously). If you wanted to perform this setting automagically, you could use the base class's Page_InitComplete event to cycle through any user controls and set the ParentForm to "this" that way.
Being in a different directory would get visual studio to give them different namespaces by default, causing the parent page class not to visible to the control.
Make sure the namespace declarations of both classes are the same, or import the parent page class namespace to the contorl with the using statement.

How come the attributes for event handler properties on ASP.NET controls have a prefix (OnLoad for the Load event handler)

This is just for a better understanding of the ASP.NET framework. When you use a control in a declarative way (that would be web form markup), you assign event handlers by their method name using an attribute that starts with On:
<asp:Button runat="server" OnClick="..."/>
But when you look at the System.Web.UI.WebControls.Button class it has an EventHandler property named Click that the delegate is assigned to:
button.Click += new EventHandler(...);
So how is this implemented? Is that just a convention followed by the parser?
I know, it's a strange question, the answer will do nothing but satisfy my curiosity.
This is a naming convention used by ASP.NET which, rather unhelpfully, looks identical to another common naming convention widely used throughout .NET. Despite the apparent similarity, these two conventions are unrelated.
The .NET-wide convention, which turns out to be irrelevant here, is that it's common for events to have corresponding methods that raise the event, and for those methods' names to be formed by adding an On prefix to the event name. For example, the Click event offered by Button is related to an OnClick method, which raises that event (as has already been stated in another answer here).
The confusing part is that the OnClick method has nothing to do with the OnClick attribute that the question concerns.
It's easy to demonstrate that the OnSomeEvent methods are irrelevant here by writing a control that doesn't have any such method. Here's the codebehind for a simple user control:
public partial class EventWithoutMethod : System.Web.UI.UserControl
{
public event EventHandler Foobar;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Foobar != null)
{
Foobar(this, EventArgs.Empty);
}
}
}
This declares a Foobar event. (It never actually raises it, but that doesn't matter for the purposes of exploration.) It does not define an OnFoobar method. Nevertheless, ASP.NET is perfectly happy for us to use the OnSomeEvent convention when we use the control:
<user:EventWithoutMethod runat="server" OnFoobar="FooHandler" />
In fact, it's not only happy for us to do that, it actually requires it. Even though my control doesn't define any member called OnFoobar—the event is called just Foobar—I have to write OnFoobar if I want to attach the event handler from my .aspx file. If I just put a Foobar attribute in there in an attempt to attach the event, the handler will never run. (Unhelpfully, ASP.NET doesn't generate an error when you do that, it just silently fails to do anything with the attribute, and the event handler never runs.)

Resources