Search code examples
c#for-loopalternating

Creating divs in code behind with strange layout?


I have a for loop which loops over a number of images and displays them as part of a user control in a web project.

I need to be able to display two images in a div and then 1 image and then two images etc..

I have the following code which puts two images in a div but havent managed to find out how to alternate between 1 and 2?

StringBuilder sb = new StringBuilder();
StringBuilder sbMain = new StringBuilder();

for (int i = 0; i < FADS.Count; i++)
{
    if(i % 2 == 0)
    sb.Append("<div class=\"featrow\">");

    FeatAdv fad = FADS[i];
    sb.AppendFormat("<a href=\"{0}\" target='BannerPage' title=\"{1}\">", params);
    sb.AppendFormat("<img src='{0}'/></a>", ImagePath.FromLocal(imagelocation));

    if (i % 2 != 0)
    {
        sb.Append("</div>");
        sbMain.Append(sb);
        sb = new StringBuilder();
    }
}

Solution

  • You can do this by changing very little of your code.

    At the moment you are opening a div before every even-numbered image

    if(i % 2 == 0)
        sb.Append("<div class=\"featrow\">");
    

    and closing after every odd-numbered image

    if (i % 2 != 0) // equivalently i % 2 == 1
    {
        sb.Append("</div>");
        sbMain.Append(sb);
        sb = new StringBuilder();
    }
    

    If you wanted the images in simple groups of three, you could replace the conditions with

    if (i % 3 == 0)
    

    and

    if (i % 3 == 2)
    

    respectively.

    But you also want to open a div before the third element and close one after the second element, so you can replace the conditions with

    if ((i % 3 == 0) || (i % 3 == 2))
    

    and

    if ((i % 3 == 1) || (i % 3 == 2))
    

    respectively.

    Note that, as with your original code, you need to check after the loop to make sure you haven't opened a div and fialed to close it - this will happen if you have a number of images one more than a multiple of three. (One more than a multiple of two, in your original code.)