Steve on February 28th, 2008

Dynamic Columns When You Don’t Know How Many Entries There Are in ASP

Here is a small bit of code, using the ASP ‘mod’ function to help you dynamically create a new row or column.

The ‘mod’ function is best explained as the remainder of a division problem. 28/9 = 3 Remainder of 1 or put another way 28/9 = 3 with a ‘mod’ of 1.

Using that information, we can tell our code to do something different when it hits a certain record in the database. For example, if you are populating a table, and you don’t know how many records are currently in the database, you might use the ‘mod’ function to create a new row automatically after every 5 records.

Say we have a list of companies that we want to present in columns, but at any one moment I don’t know how many records are in the database, but I do know that I don’t want to have a column be more than 10 companies deep.

Here is how we might tackle that problem.

<table id="companies">
<tr><td>
<%
i = 1
do until rs.eof
cellString = "<p>" & rs("Company") & "</p>"
if not i mod 10 = 0 then
response.write(cellString)
else
response.write(cellString)%> </td><td> <%
end if
i = i + 1
rs.movenext
loop
%>
</td></tr>
</table>

What is happening in the code is that we are initially setting i = 1 and then outputting the first company name in a <p> tag. We then loop through the code and add 1 to i before each new loop until we get to the 10th record, because only at the 10th record does the remainder or ‘mod’ = 0.

And then at that point, we insert the company’s name but we also drop in </td><td> to close the current cell and start a new one, in effect creating a new column.

You will note that the opening and closing <td> tags need to be outside of the code or your table format will be all screwed up.

And you can easily change the number of rows in your column by changing mod = 10 to how ever many rows you would like. ie. mod = 20, mod = 30. Other ways to use ‘mod’ with minor changes to the above code would be to create new rows when needed, or using ‘mod’ to see if you are in an even or odd numbered row to possibly alternate the colors of rows.

Work No Comments

Comments RSS

Leave a Reply