Wednesday, May 9, 2007

Passing Value to a User Control from a Web Page and Loading User Control Dynamically

This article will give you a brief idea how to load a user control dynamically and pass values to it. This can be also taken as a best example for the use of properties.

Step1: Create a web page- default.aspx and place a place holder in it.

Step2: Create a user control- my.ascx and place a label in it.

Step3:In my.ascx.cs write the following code

public string prop //property

{

set { Label1.Text = value; } //write into property

}

Step4: Pace the following tag in default.aspx

<%@ Register Src="my.ascx" TagName="my" TagPrefix="uc1" %>

Step5: Place this code in default.aspx.cs

Protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

my uc = (my)Page.LoadControl("my.ascx" ); //loading the user control dynamically

uc.prop = "anoop"; //assign the label text a value

PlaceHolder1.Controls.Add(uc);

}

1 comment:

Anonymous said...

Interesting to know.