Wednesday, 11 April 2012

ASP & CSS: dynamic style rules for database items


If you work a lot with ASP and get data from databases, you might have been in need of creating different CSS rules for each item in a recordset.
We can create dynamic CSS rules with a simple loop, assuming we know the number of items to which we will apply the rule. The point is that we don't know how many recordset items we will get from the database, but we can create rules according to different situation, as I will explain shortly.

Now follow me and see what we can do.

The recordset
We don't really need to see how to fetch data from a database in ASP (it's not the main topic in this post). We only need to bear in mind that we surely need to know the total number of items we have to deal with. When we query the database we can surely know how many records we got. We will call that number RSTotal.
Starting from the above assumptions, we can create our rules.

The code
RSTotal represent the total number of records from a recordset. We then need another variable: RSCount, which will start being equal to one. The loop will go on until RSTotal is equal to RSCount.
Dim RSCount
RSCount = 1
Do While RSCount <> RSTotal
After that we insert our CSS rules:
<style type="text/css">
#OurID<%=RSCount%> {
    font-size: 14px;
    font-weight: normal;
    text-align: left;
Then we close the loop:
RSCount = RSCount + 1
The above code will create as many rules as the total number of recordset items. It will create rules for "OurID1", "OurID2" and so on.

Why should we do such a thing?

Explanation and further development
Some of you may argue that we don't need to do a thing like I explained: we could give each element in the page the same class, and create just one rule. That is true but it's not the point here.
If you look closely to the above code, you may notice that we do have much more control over every single rule. For example we could create a different style just for the first record. Or maybe we could have different styles for odd and even records. A bit further: we can create different rules based on the position of the record in the recordset (every 5 item, for example). And so on...
We can even consider another thing. In the examples made above, we saw how to use the recordset count as the only way of identifying a specific item and assign it a rule. With the same logic, we can create different rules based on the content of the item: for example we can create a rule for product that falls in a specific category.

As you can see the possibilities are almost endless, so - again - the only limit is your imagination.

Happy coding to all of you.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.