pfinferno
pfinferno

Reputation: 1955

Creating html table filled with lists on ASP page

I have two lists:

List<string> userID = new List<string>();
List<string> dates = new List<string>();

Both of these will always have the same amount of elements (Example below):

userID = [   11    |   22    |   33    |   44    |   55    ]
dates =  [ 1/22/13 | 2/22/13 | 3/22/13 | 4/22/13 | 5/22/13 ]

What I would like to do is create an HTML table on an ASP page with two columns, filled in by the elements of the lists, with userID[0] being the first cell under the first column, and dates[0] being the first cell under the second column like so:

columnName | column2Name
---------------------------
    11     |   1/22/13
    22     |   2/22/13

Right now I have:

<table style="border:solid black 2px" width="100%">
<tr style="border-bottom:solid black 2px">
   <td align="left"><%= dateSelect %></td>
   <td align="right">Date of Report: <%= System.DateTime.Now.ToString("MM/dd/yyyy") %></td>
   </tr>
</table>

Where dateSelect is a string.

This displays a single row table, which works and is what I want at the top of the table. Below that should be the two columns with headers of my choosing, then the elements.

I'm just not sure how to go about it (haven't had much HTML experience). Should I make a Repeater which I've seen suggested in similar questions, and then add header and item templates? Or is there a simpler way of doing it?

Upvotes: 0

Views: 2023

Answers (2)

rdans
rdans

Reputation: 2157

If you don't want to use repeaters you can loop and render content in a style more similar to mvc, classic asp etc as per the example below:

<table>
  <% foreach (var myItem in g) { %>
    <tr><td><%= myItem.title %></td></tr>
  <% } %>
</table>

source: How to loop through data in WebForms like in MVC

I would add that repeaters would be the more typical approach with webforms i.e. a more expected approach for any other developer looking at your code later.

Upvotes: 1

Khazratbek
Khazratbek

Reputation: 1656

Design page:

<asp:Table ID="Table1" runat="server"></asp:Table>

In the code behind:

for(int i = 0; i < itemsnumber; i++){
    TableRow tr = new TableRow();
    TableCell tc1 = new TableCell();
    TableCell tc2 = new TableCell();
    tc1.Controls.Add(new LiteralControl("<span>" + List1[i].ToString() + "</span>"));
    tc2.Controls.Add(new LiteralControl("<span>" + List2[i].ToString() + "</span>"));
    tr.Controls.Add(tc1);
    tr.Controls.Add(tc2);
    Table1.Controls.Add(tr);
}

Upvotes: 1

Related Questions