I needed to display a set of images in a number of columns. I need to have 4 images across the page and whatever number of rows of images down. I didn’t know exactly how many images I would have in total and I needed to make sure that if the total number of images was not divisible by 4 they would still show up. This is what I came up with to make it work. I realize that using a table is cheating, but I was under the gun to get it completed.
<table style="margin: 0 auto;">
int index = 0;
double temp = (double)(Model.ChapterList.Count / 4.0);
int rows = (int)Math.Ceiling(temp);
@for (int y = 0; y < rows; y++)
@for (int x = 0; index < Model.ChapterList.Count && x < 4; x++)
<td style="padding: 10px; position: relative;">
<a target="_blank" href="@Model.ChapterList[index].PDFPath.ToString()">
<img src="@Model.ChapterList[index].ImagePath.ToString()" style="box-shadow: 2px 2px 5px #888888; width: 100%;" />
@if (@Model.ChapterList[index].ImagePath.ToString() == "../Images/default.jpg")
(Sorry for the formatting.)
I needed to figure out how many rows I really needed and if there were an odd amount of rows I needed to make sure that the extra row was added so that I didn’t miss an image. To do this I divided the number of images by 4 (you could use what ever number of columns you want) to get the number of rows. Then rounded up to get the actual number of rows needed. then just iterated through the rows adding in each image to a column.
I realize that using a table is cheating in today’s best practices. This could easily be updated to use css to make it correct. The point of the post is the calculations to make the rows and columns show up.