Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Loading user controls dynamically - Part 109

Suggested Videos
Part 106 - Raising custom events from user controls
Part 107 - Consuming user control custom events
Part 108 - Events and delegates in c#

In this video we will discuss about loading user controls dynamically. Normally, we drag and drop user controls on the webform, at design time. However, there could be several reasons in real time, for loading user controls dynamically. For example, depending on logged in user preferences like age, gender, location etc, we may want to load different user controls. Along the same line, based on Admin and Non-Admin users, different user controls should be loaded.

In most of the internet articles, I read that, if we want, the dynamically created controls, to maintain viewstate across postback, the controls should be loaded in Page_Init() event of the webform. However, I used the Page_Load() event, but the controls are still able to retain their state across postback.

Let us add the CalendarUserControl to the webform. Drag and drop, PlaceHolder control, where we want the controls to be on the page. If we don't use the PlaceHolderControl, and if we try to add controls using the following code, we may get a runtime HttpException.
Control 'CU1_txtDate' of type 'TextBox' must be placed inside a form tag with runat=server

WebForm1.aspx HTML
<form id="form1" runat="server">
    <asp:PlaceHolder ID="PlaceHolder1" runat="server">
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" 
    onclick="Button1_Click" />

Webform1.aspx.cs Code
protected void Page_Load(object sender, EventArgs e)
    CalendarUserControl calendarUserControl = 
    calendarUserControl.ID = "CU1";
    calendarUserControl.DateSelected += 
        new DateSelectedEventHandler(calendarUserControl_DateSelected);
    calendarUserControl.CalendarVisibilityChanged += 
        new CalendarVisibilityChangedEventHandler(calendarUserControl_CalendarVisibilityChanged);

protected void calendarUserControl_CalendarVisibilityChanged(object sender, CalendarVisibilityChangedEventArgs e)
    Response.Write("Calende Visible = " + e.IsCalendarVisible.ToString());

protected void calendarUserControl_DateSelected(object sender, DateSelectedEventArgs e)

protected void Button1_Click(object sender, EventArgs e)

In the next video session, we will discuss about dynamically loading standard user controls.

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.