views:

39

answers:

3

I have a datalist with products we use on our product page. I'm generating javascript for each item in the collection using:

foreach (ProductItem item in _prod.ActiveProductItemCollection)
{
    sb.Append("<script type='text/javascript'>");
    sb.Append("mboxCreate(\"product_productpage_rec\",");
}

and so on...

What I want to do is get the index of the item and append it in my stringbuilder. I'm learning asp.net and am not quite sure how to do it. Here is an example of how the code would generate ideally.

first product

<script type='text/javascript'>
mboxCreate("deandeluca_productpage_rec1")
</script>

second product

<script type='text/javascript'>
mboxCreate("deandeluca_productpage_rec2")
</script>

I'm assuming I need to do a loop of some kind but like I said before unsure of how to do one.

+1  A: 

assuming that the collection has a Count property that returns its length, why not do a simple loop like for (int i=0; i<collection.Count; i++)?

akonsu
+1  A: 

You'd better use a for-loop instead of foreach.

Danny Chen
A: 

something like this?

for (int i = 1; i <= _prod.ActiveProductItemCollection.Count; i++)
{
    sb.Append("<script type='text/javascript'>");
    sb.AppendFormat("mboxCreate(\"product_productpage_rec{0}\",", i);   
}
Hamish Smith
Should be `_rec{0}\")", i);`
Danny Chen
whoops, so it should. cheers.
Hamish Smith
I get a build error with the code above. "Cannot convert from 'string' to 'char'."
tking