Dynamic web controls generation in a dynamic HTML table

Daspoo

Regular
Joined
Jan 27, 2003
Messages
99
Location
Fort Walton Beach, Florida
Hey all. I'm wondering if anyone has any thoughts or suggestions concerning the following issue. I'm attempting to dynamically build a web form, which I know is not difficult; however, I'm trying to build a dynamic page in which web controls will exist within the cells of an HTML table. The table does not have a static number of rows so I have to create it on the fly.

Does anyone have any idea(s) as to how I can create a dynamic HTML table (within the .vb code-behind page), and add dynamic web controls inside of the table, and then have it all displayed once the Page_Load event is run? So far my attempts have led to my trying to use a LiteralControl object, only to discover that it doesn't "do" any items to be run at the server. Also, although not recommended, I tried my hand at Response.Write which served to draw everything out for me perfectly, except not contained with the "<FORM>" tag of the page - hence, no working ASP controls.

Help! Much appreciated, guys! :D
 
Yes you can do this in code.

First build the HTML table using:

Protected WithEvents mytable As system.Web.UI.HtmlControls.HtmlTable

Now what you need to do is build your rows and columns of the table:

dim row1 as New HtmlTableRow
dim col1 as New HtmlTableCell
dim col2 as New HtmlTableCell
dim col3 as New HtmlTableCell etc etc

Now you can reference all the elements of the table using the declared objects.

e.g. to add some text to the second column, just enter something like:

col2.innerHTML = "This is a test"

you can even change other parameters like vertical aligning the cell and changing the CSS Style for that cell etc:

col2.VAlign = "top"
col2.Attributes.Add("Class", "mystyle")

The specific issue you had when trying to add asp.net controls into this table is just as easy.

If you wanted to add an asp.net textbox to column 3 just type:

Dim dg As New TextBox
col3.Controls.Add(dg)

Once you have built all the required columns and rows, you must add the columns to the cells collection and the rows to the rows collection of the table as below:

row1.Cells.Add(col1)
row1.Cells.Add(col2)
row1.Cells.Add(col3)
mytable.Rows.Add(row1)

That's about it!!


tr.Cells.Add(tc(0))
 
Re:

Thanks, tonyf! After playing around with the code and what's available in .NET, I pretty much came up with the same info that you did after posting. I appreciate your input - now that I know I have someone else that's done the same type of thing, I'm even more sure that this is the way to go. Thanks again! :cool:
 
Back
Top