Question

I have a list of roughly 50~60 items that I want to be able to divide into multiple columns dynamically. I'm using a nested for loop and the lists divide properly when there are an even number of items. However, when there are an odd number of items the remainder (modulus) items get left out. I've been playing around with it for a while and have not struck gold yet. I'm hoping someone smarter than me can & will assist.

Thanks.

    for (int fillRow = 0; fillRow < numOfCols; fillRow++)
    {
            for (int fillCell = 0; fillCell < (siteTitles.Count / numOfCols); fillCell++)
            {
                linkAddress = new HyperLink();
                linkAddress.Text = tempSites[fillCell].ToString();
                linkAddress.NavigateUrl = tempUrls[fillCell].ToString();

                mainTbl.Rows[fillCell].Cells[fillRow].Controls.Add(linkAddress);
            }

      }
Était-ce utile?

La solution

Well yes, the problem is here:

fillCell < (siteTitles.Count / numOfCols)

That division will round down, so for example if there are 13 titles and numOfCols is 5, it will give 2 - which means that items 10-12 won't be used.

I suggest that actually you loop over all the items instead, and work out the row and column for each item:

for (int i = 0; i < siteTitles.Count; i++)
{
    int row = i / numOfCols;
    int col = i % numOfCols;
    // Fill in things using row, col and i
}

(It's not exactly clear what you're doing as you're using siteTitles in the loop condition and tempSites in the loop body, and you're not using fillRow when extracting the data... basically I think you've still got some bugs...)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top