Most often, we will get requirements to pass values to user control form the codebehind class. This can be achieved by 2 ways,
Using Public Properties
Declare a public property in user control and assign the value from codebehind/ASPX.
Refer the below code!
public partial class Header : System.Web.UI.UserControl
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = Name;
}
From ASPX
<uc1:Header ID="Header1" Name="CodeDigest" runat="server" />
From CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
Header1.Name = "CodeDigest";
}
Using Page Item Collection
There is new item collection packed with Page object from 2.0 framework. We can also use this collection to pass objects to usercontrols.
Note:
We can also use HttpContext object’s item collection for this.
Page CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
Page.Items.Add("Name", "CodeDigest");
}
UserControl CodeBehind
public partial class Header : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = Page.Items["Name"].ToString();
}
}
|