Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

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
this.Page.Controls.Add(LoadControl("~/UserControls/CalendarUserControl.ascx"));



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

Webform1.aspx.cs Code
protected void Page_Load(object sender, EventArgs e)
{
    CalendarUserControl calendarUserControl = 
        (CalendarUserControl)LoadControl("~/UserControls/CalendarUserControl.ascx");
    calendarUserControl.ID = "CU1";
    calendarUserControl.DateSelected += 
        new DateSelectedEventHandler(calendarUserControl_DateSelected);
    calendarUserControl.CalendarVisibilityChanged += 
        new CalendarVisibilityChangedEventHandler(calendarUserControl_CalendarVisibilityChanged);
    PlaceHolder1.Controls.Add(calendarUserControl);
}

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

protected void calendarUserControl_DateSelected(object sender, DateSelectedEventArgs e)
{
    Response.Write(e.SelectedDate.ToShortDateString());
}

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Write(((CalendarUserControl)PlaceHolder1.FindControl("CU1")).SelectedDate);
}

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

1 comment:

It would be great if you can help share these free resources