先来张图片说明下我们要实现的菜单:
这个菜单只实现了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等资料请参考其他的教程。
时间: 2024-10-10 22:21:23