Search code examples
c#asp.netasp.net-placeholder

How will I get a dynamic control in an aspx page?


I am working a project for my company. There I have encountered a problem. Therefore, I am showing an example of what I intended to do and what I am not being able to do.

In my aspx page I have button and placeholder. e.g.

 <asp:Button ID = "brnClickme" runat = "server" Text = "Click Me"onclick="brnClickme_Click" />
  <asp:PlaceHolder ID = "PH" runat = "server"></asp:PlaceHolder>

and in my aspc.cs file I have a dynamic control, say a Label that will changed its value after the Button is clicked

so I have written the code like this

    protected void Page_Init(object sender, EventArgs e)
    {
        Label label = new Label();
        label.Text = "I am in the Place holder";
        PH.Controls.Add(label);
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }


   protected void brnClickme_Click(object sender, EventArgs e)
    {
        Label label = (Label)FindControl("label");
        label.Text = "After Click I am changed!";
    }

But in the Button click event, I am not finding the Label, so I am not being able to change the text of this dynamically created label with a click. I know I have made a mistake, so Please tell me what Mistake Have I made and What am I suppose to do.

Thanks in advance


Solution

  • Try finding the control in the placeholder

    PH.FindControl("label"); 
    

    You probably want to give the label an ID to make it easier to find when you create it.

    label.ID = "findme";
    

    then

    PH.FindControl("findme");