Wednesday, August 17, 2011

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>



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();
}
}


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.

1 comment:

  1. 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.......

    ReplyDelete

PDF Arabic watermark using MVC and iTextSharp

PDF full page Arabic watermark using MVC and iTextSharp Download :  Source Code Most of the time we have requirement to  gen...