Dynamic Load or Add User Control and Maintain the View State


In this post I will explain you how to add or load user control in a page or any other user control and maintain the view state.Normally we are facing problem when we load user control on button click or any business condition in this case when page will post back control will lost its view state or in other words losing form field values on post back.This is happen because we are adding user control after page Load View State Stage for further detail you should learn asp.net page lifecycle.That means, if we want our dynamic controls to persist view state itself we must add them to the control hierarchy in the page’s Init event.

Here, I will explain the example when we want to add user control on any event.I have two user controls one is Grid view and second I will take login control and load on it into two submit buttons.

 
Adding Reference or Directive on a Webpage
 
The first thing we have to do, is declare our UserControls. It can be done either in each page where it’s used, or globally in the web.config file. There is no performance difference, but when declaring UserControls in the web.config file, the controls have to reside in a different directory than the page(s) using it for further detail check my pervious post Register Custom User Control in Web.Config File

So in the webform, add the following directive:

<%@ Register src="Controls/GridView.ascx" tagname="GridView" tagprefix="uc1" %>

<%@ Register src="Controls/LoginControl.ascx" tagname="LoginControl" tagprefix="uc2" %>

Loading dynamically

For loading user control on a page you should need to drag and drop the place holder where you want to show user control.

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Also add the two buttons to add user control on button click .

<asp:Button ID="btnGrindControl" runat="server" Text="Button" />

<
asp:Button ID="btnLoginControl" runat="server" Text="Button" />

your aspx page look like this,

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"

CodeFile="Default.aspx.cs" Inherits="_Default" %>


<%@ Register Src="Controls/GridView.ascx" TagName="GridView" TagPrefix="uc1" %>
<%@ Register Src="Controls/LoginControl.ascx" TagName="LoginControl" TagPrefix="uc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

<asp:Button ID="btnGrindControl" runat="server" Text="Button" />
<asp:Button ID="btnLoginControl" runat="server" Text="Button" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

</asp:Content>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Code Behind

In the Code Behind of the page, we add the control like this:

PlaceHolder1.Controls.Add(LoadControl("~/UserControl.ascx"));

In order to maintain the Viewstate of user control you should maintain the UserControl complete path and used this path every time on postback and load the control.

using System;

using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
public string ControlPath
{
get
{
if (ViewState["controlPath"] != null)
return Convert.ToString(ViewState["controlPath"]);
else
return null;
}

set
{
ViewState["controlPath"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
LoadUserControl();

}
private void LoadUserControl()
{
if (!string.IsNullOrEmpty(ControlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(ControlPath);
PlaceHolder1.Controls.Add(uc);
}
}



protected void btnGrindControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/GridView.ascx";
LoadUserControl();
}
protected void btnLoginControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/LoginControl.ascx";
LoadUserControl();
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

In above example I create one property name “ControlPath” for maintaining the Url of user control on button click .In LoadUserContol() I am just clearing the placeholder and adding the user control.In postback user control is adding everytime beacuse  user control was added after the page load and view state stage .There are few good articles written by Scott Mitchell on dynamically loading Controls which you will find in the following links:

Conclusion

In this article we saw how to work with dynamic controls so that their values and view state can be correctly persisted across postbacks.

Advertisements
This entry was posted in Asp.Net. Bookmark the permalink.

4 Responses to Dynamic Load or Add User Control and Maintain the View State

  1. aparna john says:

    Hi,Actually with usability tests, most web users would automatically look at theWeb Design Cochin header when they want to find other web pages. Therefore unless you want to be maverick with your website in one of the best web page design tips.Thanks…….

  2. Pavithra M says:

    It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | Dot Net Training institute in velachery

  3. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. dot net training in velachery | dot net training in chennai

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s