0

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.

user217648
  • 3,338
  • 9
  • 37
  • 61

1 Answers1

1

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.

schudel
  • 1,235
  • 2
  • 11
  • 18
  • Requst.Form["textbox1"] is empty. it seems when you add controls to a literal they just be rendered on client side and the server does not about them. – user217648 Feb 17 '15 at 08:36
  • On post back, the value should be there. You can check this by looking at the sent data using the dev tools of your browser. Also, it might be a typo textbox1 versus testbox1 – schudel Feb 17 '15 at 08:52
  • I checked request body in dev tools (Network) and the values are there. but in SaveButton_Click the values are empty. I read an article which says I have to create textboxes in Page_init not in Page_load is it right? – user217648 Feb 17 '15 at 09:36
  • I marked your answer as answer because it helped me to localize the problem. I had added the method which creates the dynamic textboxes inside if(!Page.PosteBack). – user217648 Feb 17 '15 at 10:55