22 July 2008

How to Load User Control Dynamically and also access it's property dynamically.

support u have two user control

User Control "a0"


%@ Control Language="C#" AutoEventWireup="true" CodeFile="a0.ascx.cs" Inherits="UserControlTest_a0" %

asp:TextBox ID="TextBox1" runat="server">asp:TextBox>

br /


asp:Button ID="Button1" runat="server" Text="Button" /


And there is a property to something for text value in it's CS file.

public string TextValue
{
get { return TextBox1.Text; }
set { TextBox1.Text = value; }
}


Now User Control "a1"

%@ Control Language="C#" AutoEventWireup="true" CodeFile="a1.ascx.cs" Inherits="UserControlTest_a1" %


%@ Register src="a0.ascx" tagname="ASP" tagprefix="ASP" %


Now in the page load event of this second user control I want to load "a0" user control and also want to set it's "TextValue" property.

protected void Page_Load(object sender, EventArgs e)
{
///Load Control
UserControl ucDynamic = (UserControl)LoadControl("a0.ascx");

///Add User control to the page
this.Controls.Add(ucDynamic);

///Change Property value for newely added user cotrol
///here "UserControlTest" is the name of the folder in my test web site, user have to change it
((UserControlTest_a0)ucDynamic).TextValue = "saAction";
}


It mans there are two user controls "a0" and "a1", Using "UserControl" we can add user control dynamically and to access it's property we have to convert that variable in to our user control.


0 comments :

Post a Comment