Search code examples
webformsfindcontroldynamic-controls

Find dynamically created controls inside Literal in asp.net page


Following is my code

-- the .aspx file

<div id="testDiv" runat="server"></div>

-- the .aspx.cs file

Literal lit1 = new Literal();
lit1.Text = "<table class='allocTable'>";
lit1.Text += "<tr><td><input type='text' runat='server' id='testbox1'></input></td></tr>";
... some other controls <tr><td>...
lit1.Text += "</table>"
testDiv.Controls.Add(lit1);

Now how can I find testbox1 in the .aspx.cs file? I have used FindControl on testDiv and the placeHolder but it returns null.

It seems the textboxes have not been added to the page control but they have just been rendered.


Solution

  • If you want to get the value of the textbox on post back, you could use Request.Form["testbox1"].

    If you want wo work with "real" server controls, you would use an asp:Panel in your aspx file instead of your div. In the asp.cs Init or Load method you would then add an HtmlTable to the Panel.Controls collection, HtmlTableRow(s) to the HtmlTable.Rows collection and HtmlTableCell(s) to the HtmlTableRow.Cells collection.

    As you create the input controls you are adding to the Cell.Controls collection, you can store them in private member variables.