Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Table row every 4th loop

How do I create a new table row on every 4th loop in my Razor View? This is creating a new row for each number before 4, and then quits creating new rows:

  @{
            int i = 0;
         }
         @foreach (var item in ViewBag.ProgramIdList)
         {

          if((i / 4) == 0)
          {
              @:<tr>
          }
          <td>
          <input type="checkbox" name="@item.ProgramId" id="@item.ProgramId" />   
         <label for="@item.ProgramTitle">@item.ProgramTitle</label>
         </td>
        if((i / 4) == 0) 
        {
        @:</tr>
          }
             i++;
         }
like image 805
user547794 Avatar asked Oct 05 '12 21:10

user547794


2 Answers

Use the modulo operator. For :

if((i % 4) == 0)
{
  @:<tr>
}

and

if((i % 4) == 3)
{
  @:</tr>
}

If the number of items doesn't divide into even rows, you would add the remaining cells and a closing row tag after the loop:

if ((i % 4) != 0) {
  while (i % 4) != 0) {
    @:<td></td>
    i++;
  }
  @:</tr>
}
like image 139
Guffa Avatar answered Oct 11 '22 14:10

Guffa


For those that hates the syntax higlight warning that appears with the code of the answer above, there is the solution (the mechanism is about the same):

<table>
    @for (int i = 0; i < ViewBag.MyItems.Count; i++)
    {
        var cells = 4;
        var item = ViewBag.MyItems[i];

        if ((i % cells) == 0)
        {
            @:<tr>
        }

        <td>
            @item.MyTextOrWhatever
        </td>

        if (i == (ViewBag.MyItems.Count - 1))
        {
            while ((i % cells) != 0)
            {
                @:<td></td>
                i++;
            }
        }

        if ((i % cells) == (cells - 1)) // aka: last row cell
        {
            @:</tr>
        }
    }
</table>

Each tag is in the right position (<td> inside <tr>, <tr> inside <table>), then your Visual Studio syntax highlighter will leave you in peace :-)

like image 36
T-moty Avatar answered Oct 11 '22 14:10

T-moty