tags:

views:

792

answers:

3

I want to display items as follows,

<td1>     <td2>     <td3>     <td4>
1          7         13        19
2          8         14        20
3          9         15        21
4          10        16        22
5          11        17        23
6          12        18

I am getting data (from 1......23) in a single column from database. Now I want to run a loop which will display my single columns data in the above format. Please tell me the for loop code using which I can display data in above format. Data can be more that 23 in production environment, So the logic should be as that it can handle any amount of data. I am using ASP.NET(C#).

Thanks

+2  A: 

In pseudocode (didn't test it):

int recordnum=....; //get the total number of records
int col_length=recordnum/4;

for(int i=0;i<col_length;i++)
{ for(int j=0;j<4;j++)
    print data[i+j*col_length] ;
  print "\n";
}
Riho
you should have tested it... it will show one too few rows unless the number of records is a multiple of four.
Alnitak
I left testing as an exercise for the asker
Riho
+3  A: 

I think you could use asp:DataList and bind the data to it.
Here is an example of using datalist with RepeatDirection and RepeatColumns properties.

Kb
WOW, that's coool, yes we can use this. I am trying my problem with this and will let you know if solved. Thanks for this concept.
Prashant
+2  A: 

OK, here's a corrected version of Riho's loop:

int records = ... ;                     /* the number of records */
int cols = 4;                           /* the number of columns */
int rows = (records + cols - 1) / cols; /* nb: assumes integer math */

for (int row = 0; row < rows; ++row) {

    print "<tr>";

    for (int col = 0; col < cols; ++col) {

        print "<td>";

        int offset = col * rows + row;
        if (offset < records) {
            print data[offset];
        } else {
            print "nbsp;" /* nb: should have an & but markdown doesn't work */
        }

        print "</td>";
    }

    print "</tr>";
}

The &nbsp; cell is often necessary to ensure that the rendered HTML cell has the correct background. Missing cells or cells with no data in them aren't rendered the same as normal cells.

Alnitak