比如为了实现以下嵌套效果

★ 人★
    男人  女人   老人
    小孩
★ 动物★
     狗  猫  
★ 水果★
    apple  香焦  西瓜
    菠萝   葡萄

 

代码
           <!--主菜单开始-->
           
<ASP:datalist id="Datalist1" runat="server" RepeatDirection="Horizontal" RepeatColumns="1"
            Width
="100%" OnItemDataBound="Datalist1_ItemDataBound">
            
<ItemTemplate>
             ★
<href='product_type_detail.aspx?id=<%# DataBinder.Eval(Container.DataItem,"typeid") %>'>
             
<%# DataBinder.Eval(Container.DataItem,"typename"%></a><br/>
             
<!--子菜单开始-->
              
<asp:datalist id="Datalist2" Width="100%" runat="server" RepeatColumns="3" RepeatDirection="Horizontal">
               
<ItemTemplate>
                
<href='product_type_detail.aspx?id=<%# DataBinder.Eval(Container.DataItem,"typeid") %>'>
                     
<%# DataBinder.Eval(Container.DataItem, "typename")%></a>                    
               
</ItemTemplate>
              
</asp:datalist>
             
<!--子菜单结束-->
            
</ItemTemplate>
           
</asp:datalist>
           
<!--主菜单结束-->

 

后台:

 

(1)为主DataList绑定主数据。

        void MyBind()
        {
            DBHelper helper = new DBHelper();
            string sql = "select typeid,pid,typename from product_type where typelevel=1 order by ordernum ";

            DataSet ds = new DataSet();
            ds = helper.ExecuteDataSet(sql);

            Datalist1.DataSource = ds;
            Datalist1.DataBind();
        }

 

(2)为子DataList绑定数据。

DataList嵌套的重点是要在外层DataList的ItemDataBound事件中完成对嵌套DataList的绑定。在主DataList的ItemDataBound事件中用e.Item.FindControl方法来找到嵌套层DataList的id,完后为该id绑定数据

 

        protected void Datalist1_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataList Datalist2 = (DataList)e.Item.FindControl("Datalist2");
                DataRowView rowv = (DataRowView)e.Item.DataItem;
                int pid = Convert.ToInt32(rowv["typeid"]);

                if (pid > 0)
                {
                    DBHelper helper = new DBHelper();
                    string sql = "select typeid,pid,typename from product_type where pid=" + pid;

                    DataSet ds = new DataSet();
                    ds = helper.ExecuteDataSet(sql);

                    if (ds != null)
                    {
                        try
                        {

                            Datalist2.DataSource = ds;
                            Datalist2.DataBind();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                }
            }
        }

 


 

posted on 2010-09-25 17:20  使名扬  阅读(290)  评论(0编辑  收藏  举报