使用嵌套模板(NestedRepeater|NestedDataList)

來源:互聯網
上載者:User

  上自己申請的留言薄看了一下,有人說非常漂亮,問是怎麼做的,其實非常簡單,無非就是三大操作,痛點就在於如何?取出對應留言的回複(其實也不算難),而解決這個可以用嵌套模板來實現,巧妙點地話,連這個都可以不用做.

  所謂嵌套模板就是在一個模板中加入另一個模板,如

 1<asp:Repeater ID="parent" Runat="server">
 2                <ItemTemplate>
 3                    編號:<%# DataBinder.Eval(Container.DataItem,"id")%>
 4                    留言:<%# DataBinder.Eval(Container.DataItem,"content")%>
 5                    <br>
 6                    <asp:Repeater ID="child" Runat="server">
 7                        <ItemTemplate>
 8                            回複:<%# DataBinder.Eval(Container.DataItem,"reply")%><br>
 9                        </ItemTemplate>
10                    </asp:Repeater>
11                </ItemTemplate>
12            </asp:Repeater>

在後置代碼Load中寫入(假設父模板為parent,子模板為child)

OleDbConnection con = new OleDbConnection(@"../gb.mdb");
            OleDbDataAdapter da = new OleDbDataAdapter("select * from guestbook",con);
            OleDbDataAdapter da2 = new OleDbDataAdapter("select * from reply",con);

            DataSet ds = new DataSet();
            da.Fill(ds,"guestbook");
            da2.Fill(ds,"reply");

            ds.Relations.Add("relation",ds.Tables[0].Columns["id"],ds.Tables[1].Columns["id"]);

            parent.DataSource = ds.Tables[0].DefaultView;
            parent.DataBind();

            con.Close();

主要是為兩個表之間添加關係,當前如果一個表就什麼都不用做了.

接著寫Repeater的 ItemDataBound 事件,這個很關鍵.

DataRowView dv = e.Item.DataItem as DataRowView;

            child = e.Item.FindControl("child") as Repeater;
            child.DataSource  = dv.CreateChildView("relation");
            child.DataBind();

通過FindControl()來尋找子模板並賦資料來源.

上面的思路其實可以理解為兩個表間的父子關係映射到嵌套模板上去.

隨手寫的代碼,亂七八糟的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.