title: How to use the FindControl function to find a dynamically generated control?
body: <p>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:</p>
  
  <pre><code>TextBox tb = new TextBox();
  tb.Text = quest.Value;
  tb.ID = quest.ShortName.Replace(" ", "");
  ((PlaceHolder)e.Item.FindControl("ph_QuestionInput")).Controls.Add(tb);
  </code></pre>
  
  <p>I am using the following code to retrieve the values that have been entered into the TextBox:</p>
  
  <pre><code>foreach (ListViewDataItem di in lv_Questions.Items)
  {
      int QuestionId = Convert.ToInt32(((HiddenField)di.FindControl("hf_QuestionId")).Value);
      Question quest = dc.Questions.Single(q =&gt; q.QuestionId == QuestionId);
      TextBox tb = ((TextBox)di.FindControl(quest.ShortName.Replace(" ","")));
      //tb is always null!
  }
  </code></pre>
  
  <p>But it never finds the control.  I've looked at the source code for the page and the control i want has the id:</p>
  
  <p>ctl00_cphContentMiddle_lv_Questions_ctrl0_Numberofacres</p>
  
  <p>For some reason when I look at the controls in the ListViewDataItem it has the ClientID:</p>
  
  <p>ctl00_cphContentMiddle_lv_Questions_ctrl0_ctl00</p>
  
  <p>Why would it be changing Numberofacres to ctl00?  Is there any way to work around this?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>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?  </p>
  
  <p>If so am I just SOL when it comes to retrieving the values in my dynamic controls from my OnClick event?</p>
  
  <p><strong>UPDATE 2:</strong></p>
  
  <p>So i changed the code i had in my Page_Init event from:</p>
  
  <pre><code>protected void Page_Init(object sender, EventArgs e)
  {
          if (!this.IsPostBack)
          {
              //databind lv_Questions
          }
  }
  </code></pre>
  
  <p>to:</p>
  
  <pre><code>protected void Page_Init(object sender, EventArgs e)
  {
              //databind lv_Questions
  }
  </code></pre>
  
  <p>And it fixed my problem.  Still a little confused as to why I want to databind regardless of whether it's a postback or not but the issue is resolved.</p>