Reputation: 198
I am trying to arrange a list of checkboxes into 3 columns such as:
A F L
B G M
C H N
D I O
E K ...
Currently I have code which does this, but if the number of checkboxes isn't divisible by 3 then it goes out of range and throws a null reference exception. The number of checkboxes that I have can vary so I can't hardcoe it to a number which is divisible by 3.
This is the code that I currently have:
@{
var rows = (Model.BettingOffices.Count()) % 10 == 0
? (Model.BettingOffices.Count) / 10
: ((Model.BettingOffices.Count) / 10) + 1;
}
<table>
@for (int i = 0; i < rows; i++)
{
<tr>
<td width="400">
@Model.BettingOffices.Skip(i).FirstOrDefault().OfficeName
<input name="selectedShops" type="checkbox"
value="@Model.BettingOffices[i].OfficeName"/>
</td>
<td width="400">
@Model.BettingOffices.Skip(i + rows).FirstOrDefault().OfficeName
<input name="selectedShops" type="checkbox"
value="@Model.BettingOffices[i + rows].OfficeName" />
</td>
<td width="400">
@Model.BettingOffices.Skip(i + rows * 2).FirstOrDefault().OfficeName
<input name="selectedShops" type="checkbox"
value="@Model.BettingOffices[i + rows * 2].OfficeName" />
</tr>
}
</table>
Is there any way I can stop it from going out of range and throwing the exception?
Upvotes: 1
Views: 3478
Reputation: 239240
Just utilize CSS and stop using HTML for layout style.
HTML
<ul class="checkboxes">
<li><label><input type="checkbox"/> CheckBox 1</label></li>
<li><label><input type="checkbox"/> CheckBox 2</label></li>
<li><label><input type="checkbox"/> CheckBox 3</label></li>
...
</ul>
CSS
.checkboxes ul, .checkboxes li {
margin:0;
padding:0;
list-style:none;
}
.checkboxes li {
display:inline-block;
width:33.3333%;
}
You might need to tweak the display a little, but that will get you mostly there. The list items will fill as much of the line as possible and then automatically wrap to the next line, so based on a width of 33.3333% you'll get 3 per line.
Or, even better go fully responsive by utilizing some CSS library with grids (you can roll your own, but why?) For example, with Bootstrap, you could do:
<ul class="list-unstyled row">
<li class="col-md-4 col-xs-6"><label><input type="checkbox"/> CheckBox 1</label></li>
<li class="col-md-4 col-xs-6"><label><input type="checkbox"/> CheckBox 2</label></li>
<li class="col-md-4 col-xs-6"><label><input type="checkbox"/> CheckBox 3</label></li>
...
</ul>
No additional CSS is required and you get the bonus of being able to change how many appear on a line responsively. For example, in the code above, medium-sized and up displays get three per line (Bootstrap uses a 12 column grid, so one-third of that is 4), while a very small display like a phone in portrait will get only 2 (12/2 = 6). This is much more flexible than using HTML, especially with tables which will absolutely bork the display on a small device.
Upvotes: 5