2009-01-25 108 views
1

我想如下顯示的項目,如何以表格格式顯示單列數據?

<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   

我得到的數據(從1 ...... 23)從數據庫中的單個列中。現在我想運行一個循環,以上面的格式顯示我的單列數據。 請告訴我使用哪種循環代碼,我可以以上述格式顯示數據。在生產環境中數據可以多於23個,所以邏輯應該是它可以處理任何數量的數據。我正在使用ASP.NET(C#)。

感謝

回答

2

OK,這裏的Riho的循環修正版本:

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>"; 
} 

&nbsp;細胞往往是必要的,以確保所提供的HTML細胞具有正確的背景。缺少沒有數據的單元格或單元格與正常單元格不同。

2

僞代碼(沒有測試):

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"; 
} 
+1

你應該測試過它......它會顯示一行太少,除非記錄數是四的倍數。 – Alnitak 2009-01-25 14:55:31

+0

我離開測試作爲一個練習的提問者 – Riho 2009-01-25 15:40:36

3

我想你可以用asp:DataList和數據綁定到它。
以下是使用datalist以及RepeatDirection和RepeatColumns屬性的示例。