How to use the FindControl function to find a dynamically generated control?
Posted
by Abe Miessler
on Stack Overflow
See other posts from Stack Overflow
or by Abe Miessler
Published on 2010-06-10T21:00:00Z
Indexed on
2010/06/11
0:02 UTC
Read the original article
Hit count: 237
ASP.NET
I have a PlaceHolder control inside of a ListView that I am using to render controls from my code behind. The code below adds the controls:
TextBox tb = new TextBox();
tb.Text = quest.Value;
tb.ID = quest.ShortName.Replace(" ", "");
((PlaceHolder)e.Item.FindControl("ph_QuestionInput")).Controls.Add(tb);
I am using the following code to retrieve the values that have been entered into the TextBox:
foreach (ListViewDataItem di in lv_Questions.Items)
{
int QuestionId = Convert.ToInt32(((HiddenField)di.FindControl("hf_QuestionId")).Value);
Question quest = dc.Questions.Single(q => q.QuestionId == QuestionId);
TextBox tb = ((TextBox)di.FindControl(quest.ShortName.Replace(" ","")));
//tb is always null!
}
But it never finds the control. I've looked at the source code for the page and the control i want has the id:
ctl00_cphContentMiddle_lv_Questions_ctrl0_Numberofacres
For some reason when I look at the controls in the ListViewDataItem it has the ClientID:
ctl00_cphContentMiddle_lv_Questions_ctrl0_ctl00
Why would it be changing Numberofacres to ctl00? Is there any way to work around this?
UPDATE:
Just to clarify, I am databinding my ListView in the Page_Init event. I then create the controls in the ItemBound event for my ListView. But based on what @Womp and MSDN are saying the controls won't actually be created until after the Load event (which is after the Page_Init event) and therefore are not in ViewState? Does this sound correct?
If so am I just SOL when it comes to retrieving the values in my dynamic controls from my OnClick event?
© Stack Overflow or respective owner