decoder
decoder

Reputation: 926

n items show in 3 column logic

I have n items.I want to show it in 3 column in View page.

@foreach (var x in ViewBag.list)
{
<tr><td>@x.Name</td></tr>
}

But I want to show it in 3 column.

<tr><td>@x.Name</td><td>@x.Name</td><td>@x.Name</td></tr>

Then what is the logic for this?Anyone helps me out.

Upvotes: 1

Views: 163

Answers (2)

Philip Pittle
Philip Pittle

Reputation: 12295

You can do this with two for loops. One for row and one for columns:

@for (var row = 0; row < ViewBag.list.Count(); row++)
{
    <tr>
        @for (var col = 0; (col + row * 3)< ViewBag.list.Count() && col < 3; col++)
        {
           <td>@ViewBag.list.ElementAt(row * 3 + col).Name</td>
        }
    </tr>
}

And if you want to change the number of td elements per row, just replace 3 with a variable or hard code to a different number.

Upvotes: 1

decoder
decoder

Reputation: 926

Anyway this works for me.

  @{
            int count = 0;
            var tr = new HtmlString("<tr>");
            var trclose = new HtmlString("</tr>");
            <div class="panel-body noPad">
                <table class="table table-hover pdSbasic">
                    <tr>
                        @foreach (var pd in ViewBag.PDList)
                        {
                            <td><input type="checkbox" class="form-control" /></td>
                            <td><input type="hidden" class="pdId" value="@pd.PollidutId" />@pd.PollidutName</td>
                            count++;

                            if (count % 3 == 0)
                            {
                                @tr;
                                @trclose; 
                            }
                        }
                    </tr>
                </table>
            </div>
        }

Upvotes: 0

Related Questions