Est. Reading Time: 2 minutes
In Dot Net, as with most web development, there seems to be several ways to accomplish the same task. Some may be better based upon maintainability, clarity, etc. In some cases it’s just preference.
I had such a case recently when I was tasked with making a field in a repeater red if a quantity value was negative. I know, the obvious way would be to use the ‘findControl’ method within the ‘OnItemDataBound’ event, checking the quantity for a less than zero condition and then setting the color property on the field in question to red.
I wondered if I could walk on the wild side and accomplish the same thing by supplying the color to the repeater with the data from the DB and not invoking the ‘OnItemDataBound’ event at all. Take a look at the snippet of code below to see how the repeater was defined for this task. Note the column ‘OrderNo’ – this is the column to make red if the quantity is negative. The quantity is not to be displayed in the repeater.
. . . <ItemTemplate> <tr> <td><span style=”color:<%#Container.dataItem(“color”) %>”><%#Container.DataItem(“OrderNo”)%></span></td> <td><%#Container.DataItem(“SalesPersonName”)%></td> <td><%#Container.DataItem(“CustomerNo”)%></td> <td><%#Container.DataItem(“CustomerName”)%></td> . . .
All I have to do now is supply the color that I want the field to be as a column named ‘color’. Now let’s take a look at the select statement to do that:
SELECT o.OrderNo, ISNULL(o.SalesPersonName, ””) SalesPersonName, ISNULL(o.CustomerNo,””) CustomerNo, o.CustomerName, (select case when min(oi.Quantity) < 0 then ”red” else ”black” end from OrderItems oi where oi.OrderNo = o.orderno) as color FROM Orders o
And Voila!! The repeater field obtains its color from the data selected from the DB. Now I know this is not as radical as stopping the oil leak at the Gulf Coast (or event the one in my leaf blower for that matter), but a different twist none the less.
Now, pardon me while I go work on my leaf blower -