Click here to Skip to main content
15,878,748 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created few HTML controls dynamically on Page load.
My Code looks like this:

<pre>Protected Sub Page_Load(sender as Object, e As EventArgs) Handles Me.Load
      Dim sb As New StringBuilder
      Dim i as Integer = 0
      sb.Append("<table class ='tabledata' id='tblContent'>")
        For Each item As myObject In myList
            i += 1
            sb.Append("<textarea runat='server' id=txt_comments" & i & " 
                        name='txt_comments' rows='5' cols='60'></textarea></td>")          
        myDiv.InnerHtml = sb.ToString 
     End Sub  

From the above code,
I am creating
HTML control dynamically on Page load by using stringbuilder and finally assiging this string to my div which is present in .aspx page

<div id="myDiv" runat="server">

I am able to view my dynamically created controls on Page load.

Now I want to access the values from these textboxes in a button click event(Save).

How do i do that?
Any Help?
Thanks in advance.

What I have tried:

I tried using Page.FindControl method. But it is throwing null reference errors.
Updated 14-May-18 22:59pm
[no name] 14-May-18 23:24pm    
Saying you "used" a method (FindControl); "but it didn't work"; is not particularly "informative".

Shall we "guess" at some answers and have you run around?

1 solution

Forget the "runat" attribute, that doesn't work on controls created this way which are effectively basic html controls. Second you need a unique name for the element, might as well make it the same as the id

sb.Append("<textarea id=txt_comments" & i & " 
                        name='txt_comments" & i & "' rows='5' cols='60'></textarea></td>")   

In your code-behind you can read the value from the Request.Form collection based on the name


The alternative would be to actually create server-side controls like a TextBox and add it to the page's Controlls collection. If you google " create dynamic controls" you'll find lots of examples of how to do that.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900