2012-12-03 59 views
1

我是一種新的SQL和asp.net,並試圖創建一個論壇應用程序。我創建了兩個表格。對於每個類別,顯示其子類

SELECT 
    forum_categories.CategoryName, forum_subcategories.SubCategoryName 
FROM  
    forum_categories 
LEFT JOIN 
    forum_subcategories ON forum_categories.CategoryId = forum_subcategories.CategoryId 

enter image description here

這就是查詢返回:和我使用此查詢選擇表中的數據

enter image description here

現在我需要的是爲每個類別名稱我需要顯示它的子類別。我爲此使用了一個ListView:

<asp:ListView ID="ListView1" runat="server" DataSourceID="ForumDataSource"> 
    <ItemTemplate> 
     <div id='<%#Eval("CategoryName") %>' class="PostCategories"> 
      <h2><asp:Label ID="Label1" runat="server" Text='<%#Eval("CategoryName") %>'></asp:Label></h2> 
      <table class="ForumPosts"> 
       <thead> 
        <td>Category</td> 
        <td>Posts</td> 
        <td>Last Post</td> 
       </thead> 
       <tbody> 
        <tr> 
         <td><asp:Label ID="Label2" runat="server" Text='<%#Eval("SubCategoryName") %>'></asp:Label></td> 
        </tr> 
       </tbody> 
      </table> 
     </div>   
    </ItemTemplate> 
    <EmptyDataTemplate> 
     <p>No Data Found</p> 
    </EmptyDataTemplate> 
</asp:ListView> 
<asp:SqlDataSource ID="ForumDataSource" runat="server" 
    ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" 
    ProviderName="System.Data.SqlClient" 
    SelectCommand="SELECT forum_categories.CategoryName, forum_subcategories.SubCategoryName FROM forum_categories LEFT JOIN forum_subcategories ON forum_subcategories.CategoryId = forum_categories.CategoryId"> 
</asp:SqlDataSource> 

現在,大家可能已經從代碼中理解了這個返回8個表。

我想得是每個類別以顯示它的子類data.In這種情況下,應該只有3桌

我應該如何看待這個問題?

這應該使用SQL解決還是使用服務器端語言操作接收的數據?

回答

2

我不是ListViews的忠實粉絲。但你可以試試這個,

你需要兩個列表視圖。外部列表視圖和內部列表視圖。

外一個將循環的類別,因此它應該只給你三個表。確保你只選擇不同的。

然後內部列表視圖將遍歷每個CategoryID並獲取鏈接到CategoryID的子類別。