Question

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

Was it helpful?

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"); 

OTHER TIPS

You have not given your control an ID when creating it - this ID is what FindContorl uses in order to find that control.

You should also invoke FindControl on the container you added it to (PH in your case), as podiluska answered.

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

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

You have to recreate the Dynamic Controls in INIT as you have already done. and when you are searching for the LABEL in Button Click Try calling templateFormPlaceholder.FindControl instead.

Read this. It might help Get text from dynamically created textbox in asp.net

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top