2010-06-20 41 views
0

我想用一個DataList和流標記來創建這樣的事情:如何在一個查詢創建類別和列表使用LINQ

|-----------------------| 
|  Title   | 
|-----------------------| 
| [x] Title    | 
| [x] Title    | 
| ...     | 
------------------------- 

我有一個表(在LINQ2SQL建模)Foo具有這些領域

int id; 
int? parentId; 
string title; 
Foo Parent; 
EntitySet<Foo> Children; 

現在,當存在空父代時,這意味着它是頂級類別,並且如果父代具有值,則它是類別列表的一部分。

我創建了一個DataList,並採用了LinqDataSource與查詢,看起來像這樣:

<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
    ContextTypeName="MyNameSpace.FooDataContext" 
    Select="new (Title, Children)" TableName="Foo" 
    Where="ParentID = NULL"> 
</asp:LinqDataSource> 

<asp:DataList ID="FooList" runat="server" DataSourceID="LinqDataSource1" 
    BorderColor="Black" BorderWidth="1px" RepeatLayout="Flow"> 
    <ItemTemplate> 
    <asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' /> 
    <br /> 
    <asp:Repeater ID="Repeater1" runat="server" DataSourceID="<%# Eval("Children") %>"> 
     <ItemTemplate> 
      <asp:CheckBox ID="Checks" Text="<%# Eval("Title") %>" runat="server" /> 
     </ItemTemplate> 
    </asp:Repeater> 
    </ItemTemplate> 
</asp:DataList> 

這顯然是行不通的。 如何在DataList項目的中繼器中使用Children集合?

回答

1

我想這與我的模式表和它的作品OK.The訣竅是使用我使用Scool的實體,而教師的實體的集合Datalist.See標記below.Note的ItemDataBound事件

<asp:DataList ID="DataList1" runat="server" DataKeyField="id" 
    DataSourceID="LinqDataSource1" Width="246px" 
    onitemdatabound="DataList1_ItemDataBound"> 
    <ItemTemplate> 
     name: 
     <asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' /> 
     <div style="border:solid blue 3px;padding:2px;"> 
     <asp:Repeater ID="rptteachers" runat="server" > 
     <ItemTemplate> 
    <asp:Label ID="kllj" runat="server" Text='<%# Eval("name") %>' ></asp:Label> 
    <asp:Label ID="Label1" runat="server" Text='<%# Eval("quals") %>' ></asp:Label> 
    </ItemTemplate> 
     </asp:Repeater> 
     </div> 
    </ItemTemplate> 
</asp:DataList> 

然後,將以下內容添加到後面的代碼中。

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) 
    { 

     Repeater r = e.Item.FindControl("rptteachers") as Repeater; 
     if (r == null) return; 
     if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==  ListItemType.AlternatingItem) 
     { 
      school sc = e.Item.DataItem as school; 
      if (sc == null) return; 
      r.DataSource = sc.Teachers; 
      r.DataBind(); 
     } 
    } 
+0

是的,這是我基本上想到的解決方案。事實上,它幾乎是相同的。 – 2010-06-21 07:24:50