Wednesday, September 23, 2015

Loading user controls dynamically

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.

If you are searching life partner. your searching end with now offer free matrimonial website which offer free message, free chat, free view contact information. so register here : Free matrimonial website