前臺代碼:
<%@ Import Namespace="System.Data" %>
<asp:DataList ID="Parent" runat="server" Height="134px" Width="133px" OnInit="Parent_Init">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("QuestionContent") %>' Font-Bold="True" ForeColor="Red"></asp:Label>
<asp:DataList ID="Child" runat="server" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("Myrelations") %>' ForeColor="Green">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "[\"AnswerContent\"]")%>'></asp:Label>
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
</asp:DataList>
注意:紅色部分為子DataList,"Myrelations"為DataList間的關連名稱
後臺代碼:
String connStr = ConfigurationManager.ConnectionStrings["ResearchProjectConnectionString"].ConnectionString; //讀取WEB.CONFIG連接字串
SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter SqlDa1 = new SqlDataAdapter("select * from Question", conn);//父DataList
SqlDataAdapter SqlDa2 = new SqlDataAdapter("select * from Answer", conn);//子DataList
DataSet ds = new DataSet();
SqlDa1.Fill(ds,"Question");
SqlDa2.Fill(ds,"Answer");
ds.Relations.Add("Myrelations", ds.Tables["Question"].Columns["QuestionOrder"], ds.Tables["Answer"].Columns["QuestionOrder"]); //建立關聯
Parent.DataSource = ds.Tables["Question"]; //父DataList
Page.DataBind();
conn.Close();
留言列表