2014-03-03 170 views
1

後,我跑我的查詢我已經得到了結果到一個DataTable如下面的(這只是一個簡單的結果集):嵌套的SQL查詢結果列表

food_cat food 
----------------------- 
vegit  carrot 
vegit  onion 
vegit  tomato 
fruit  cherry 
fruit  banana 
fruit  orange 

我想列出的結果通過food_cat分組在一個無序列表中。

<h3> Vegit </h3> 
<ul> 
    <li>carrot</li> 
    <li>onion</li> 
    <li>tomato</ti> 
</ul> 
<h3>fruit</h3> 
<ul> 
    <li>cherry</li> 
    <li>banana</li> 
    <li>orange</li> 
</ul> 

我已經嘗試了一些forifwhile控制,但無法找到一個很好的解決方案。

+0

您是否想要在sql級別或演示級別生成UL/LI元素? – gh9

+0

@ gh9在演示級別。但爲什麼不在sql級別,如果它會更快 – zkanoca

+1

看看嵌套中繼器:http://stackoverflow.com/questions/3571363/nested-repeaters-in-asp-net –

回答

0

謝謝@zibidyum,你的技術讓我得到了一個解決方案。但最終的解決辦法是:

public bool firstcat; // defined at before Page_Load method 
public int temp_cat; // defined at before Page_Load method 


for (int i = 0; i < dt.Rows.Count; i++) 
{ 
    if (temp_cat != Convert.ToInt32(dt.Rows[i]["food_cat"])) 
    { 
     if (i > 0 && !firstcat) 
      content.InnerHtml += "</ul>"; //solution's most critic point is here 

     content.InnerHtml += "<ul>" 
    } 

    content.InnerHtml += String.Format("<li>{0}</li>", dt.Rows[i]["food"].ToString()); 

    temp_cat = Convert.ToInt32(dt.Rows[i]["food_cat"]); 
} 

歡迎任何更好的解決方案,建議和/或想法。

1

因爲你不提供表名等我會盡量給出一般的答案。

string previous_food_cat = ''; 
bool firstEntrance = true 

while(trace resultSet until no elements left) 
{ 
    if resultSet.food_cat != previous_food_cat //check if food_cat value changed 
    { 
     if (!firstEntrance) //if not first entrance close the <ul> tag before opening new one 
     { 
      print </ul> 
     } 

     print <h3> resultSet.food_cat </h3> //open new <h3> tag 
     print <ul> //open new <ul> tag 


     previous_food_cat = resultSet.food_cat //update previous_food_cat for new food_cat value 
     firstEntrance = false //set firstEntrance false so that ul tqags should be closed 
    } 

    print <li> resultSet.food </li> 
}