getting index of itemcollection
I have a datalist with products we use on 开发者_如何学JAVAour 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.
You'd better use a for-loop
instead of foreach
.
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++)?
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);
}
精彩评论