[web] ASP.NET Control Arrays

Started by
1 comment, last by Codejack 16 years, 10 months ago
I want to create an array of user-defined web controls, based on a collection of items (populated through a database, but how the list is collected shouldn't be an issue). I want to have a table with rows, where each row contains a control whose properties are customized based on the collection. Something like this table: ------------------------------ * [Control based on 1st row] * *----------------------------* * [Control based on 2nd row] * *----------------------------* * [Control based on 3rd row] * ------------------------------ The code would probably look something like this: For each Item in ArrayOfItems 'define a new row in the table 'define a new instance of the control 'set control properties based on Item Next So how can I achieve this in ASP.NET 2.0? (preferably in VB, but C# works fine too) How can I program the page to show a run-time created table and customize elements in that table at run-time? PS: I use Visual Web Developer 2005
Advertisement
I'm not quite sure I get what you're asking.

You have an array of arbitrary controls from some source that doesn't matter.

You want to instantiate those controls and display them one per row?

Depending on how the information is stored, it seems that you could use a Factory class to output the controls, and as far as the rows go, I'd just output them in floating divs: they'll act like a table if they are all floated left. If you want one control per row, just make sure 2 divs can't fit on one line.
I would put a Placeholder control on the page where you want the table to appear. Then I would override the OnInit() method and build a string that contains the code of the table (HTML as well as the ASP.Net tags). You would then parse the string and build the controls dynamically, before the page loads, and add them as children of the Placeholder:

override protected void OnInit(EventArgs e){  String TableStr = "<table width=""100%"">";  foreach Item in ArrayOfItems  {    TableStr += "<tr><td>";    TableStr += "<asp:Button ID=""Meh"" runat=""server"" />"; // Or whatever    Tablestr += "</td></tr>";   }  TableStr += "</table>";  Control ctrl = Page.ParseControl(TableStr);  Placeholder.Controls.Add(ctrl);}

This topic is closed to new replies.

Advertisement