Liron Harel
Liron Harel

Reputation: 11247

Wrap each 3 items with HTML Wrapper code in ForEach loop C#

I need to build an HTML code structure in C# code behind. The code inserted an HTML item that occupies 3 columns in a 12 columns Row (I'm using Zurb Foundation).

I iterate over over a collection of items in a foreach loop.

I want to add a <div class='row'>[item html code here]</div> code that will wrap the 3 column items.

Item code is something like this:

<div class='column large-4 medium-4- small-12' >some content</div>

What logic should I use (C#) in order to be able to inject the item HTML code inside the row code every three items?

My complications start when I need to separate the opening tags (<div class='row'>) with the closing tag (</div>) and put the items codes (the column divs) inside.

Assume large number of items that needs to iterate over.

The results html should look something like this if for example I have 7 items:

<div class='row'>
 <div class='column large-4'>item 1</div>
 <div class='column large-4'>item 2</div>
 <div class='column large-4'>item 3</div>
</div>
<div class='row'>
 <div class='column large-4'>item 4</div>
 <div class='column large-4'>item 5</div>
 <div class='column large-4'>item 6</div>
</div>
<div class='row'>
 <div class='column large-4'>item 7</div>
</div>

Upvotes: 3

Views: 863

Answers (3)

SlaneR
SlaneR

Reputation: 714

string BuildItems(int itemCount, int colsPerRow) {
    StringBuilder sbItemHTML = new StringBuilder();
    bool divBegin = true, divClosed = false;
    for ( int i = 0; i < itemCount; i++ ) {
        if ( divBegin ) {
            sbItemHTML.AppendLine("<div class='row'>");
            divBegin = false;
            divClosed = false;
        }

        sbItemHTML.AppendLine("<div class='column large-4'>item " + i + "</div>");
        if ( (i % colsPerRow == 0) && i > 0 ) {
            sbItemHTML.AppendLine("</div>");
            divBegin = true;
            divClosed = true;
        }
    }

    if ( !divClosed )
        sbItemHTML.AppendLine("</div>");

    return sbItemHTML.ToString();
}

how about you to try this code??

Example for use: BuildItems(7, 3);

Upvotes: 2

Ahmed
Ahmed

Reputation: 525

How about using Zurb Foundation block-grid?

Upvotes: 2

Techie
Techie

Reputation: 1491

If you use a counter in for loop; it would help to check by dividing the counter with 3 and check if the returned value is a complete number. If yes, then add the div closing tag (and next div opening tag). example below.

if (Math.Abs(i / 3) == (i / 3)) { 
str = str + "<div class='column large-4'>" + value + "</div>" + "</div><div class='row'>";
}
else{
str = str + "<div class='column large-4'>" + value + "</div>";
}

Upvotes: 1

Related Questions