Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi!

Let's say I have a usercontrol called LabelHolder. Within that I have a label like this:
<asp:Label ID="lbCan" runat="server" Text=""></asp:Label>


In a page that holds that user control (lets say Deafult.aspx) how do I (without using the FindControl method, as it is inefficient) get to set the label text property from the Default.aspx.cs file

So what I wish for i something like:

C#
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LabelHolder lH = new LabelHolder();
        lH.lbCan.Text = "foo"; //This is what I wish would work but it doesn't
        form1.Controls.Add(lH);

    }
}


Very greatful for any tips!

Thanks
Posted

You could add an accessor property to your LabelHolder control to do it for you.

C#
public class LabelHolder
{
....

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


so your code becomes

C#
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LabelHolder lH = new LabelHolder();
        lh.Text = "foo"; 
        form1.Controls.Add(lH);

    }
}
 
Share this answer
 
v2
Create a Property in the user control:


public string Name
{
set { lbCan.Text = value; }
get { return lbCan.Text; }
}


In the the Default.aspx page just assign a value to that property.

ucTest.Name = "hasan";
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900