標籤:
先來張圖片說明下我們要實現的菜單:
這個菜單只實現了2級哈。
我採用的方法是嵌套2個Repeater。
先看下資料庫中的表結構:
資料:
上代碼:
aspx:
- <asp:Repeater ID="rptMenus" runat="server"
- onitemdatabound="rptMenus_ItemDataBound">
- <HeaderTemplate>
- <ul class="mnuLevel01">
- <li id="mnuHome"><a href="#">首頁</a></li>
- </HeaderTemplate>
- <ItemTemplate>
- <li class="multiItem">
- <a target="<%#DataBinder.Eval(Container.DataItem,"target") %>" href="<%#DataBinder.Eval(Container.DataItem,"Url") %>"><%#DataBinder.Eval(Container.DataItem,"Title") %></a>
- <asp:Repeater ID="rptSubMenus" runat="server">
- <HeaderTemplate>
- <ul class="mnuLevel02">
- </HeaderTemplate>
- <ItemTemplate>
- <li><a href="<%#DataBinder.Eval(Container.DataItem,"Url") %>"><%#DataBinder.Eval(Container.DataItem,"Title") %></a></li>
- </ItemTemplate>
- <FooterTemplate>
- </ul>
- </FooterTemplate>
- </asp:Repeater>
- </li>
- </ItemTemplate>
- <FooterTemplate>
- </ul>
- </FooterTemplate>
- </asp:Repeater>
cs代碼:
- private DataSet dsMenus;//菜單
-
- protected void Page_Load(object sender, EventArgs e)
- {
- //綁定主菜單
- string connStr = "Data Source=ip地址;Initial Catalog=資料庫名;User Id=sa;password=密碼;";
- //SqlConnection conn = new SqlConnection(connStr);
- //conn.Open();
-
- string cmdText = "SELECT * FROM EP_menus WHERE status=1 ORDER BY orderid ASC,id ASC";
- //SqlCommand cmd = new SqlCommand(cmdText, conn);
-
- SqlDataAdapter adapter = new SqlDataAdapter(cmdText, connStr);
- dsMenus = new DataSet();
- adapter.Fill(dsMenus);
-
- DataView dvTopMenus = new DataView(dsMenus.Tables[0]);
- dvTopMenus.RowFilter = "[parent]=0";
- rptMenus.DataSource = dvTopMenus;
- rptMenus.DataBind();
- }
- protected void rptMenus_ItemDataBound(object sender, RepeaterItemEventArgs e)
- {
- if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
- {
- Repeater rptSMenus = (Repeater)e.Item.FindControl("rptSubMenus");
- DataRowView drv = (DataRowView)e.Item.DataItem;
-
- int pMenu = Convert.ToInt32(drv["id"]);//父級菜單id
- //if (pMenu != 0)
- //{
- DataView dvSubMenus = new DataView(dsMenus.Tables[0]);
- dvSubMenus.RowFilter = "[parent]=" + pMenu;
-
- if (dvSubMenus.Count > 0)
- {
- rptSMenus.DataSource = dvSubMenus;
- rptSMenus.DataBind();
- }
- //}
- }
- }
這裡只是個大體的思路和代碼,具體的Repeater等資料請參考其他的教程。
(轉)asp.net(C#)手記之Repeater與兩級菜單