标签:div htm jpg default 实现 comm close object control
这几天一直打算做个从数据读取导航菜单的效果,以前做的时候都是写死的(太死了),好了话不多说,先看效果!
我是个小菜,高手请不要喷!我在网上查了好久,说用menu控件,但是我用了不太好!最后我决定用repeater的嵌套来实现这个效果。先数据库结构吧!
前台的代码:
1 <body> 2 <form id="form1" runat="server"> 3 <div class="menu"> 4 <ul class="nav"> 5 <asp:Repeater ID="rptNav" runat="server" OnItemDataBound="rptNav_ItemDataBound"> 6 <ItemTemplate> 7 <li><a href=‘<%# DataBinder.Eval(Container.DataItem,"navUrl")%>‘> 8 <%# DataBinder.Eval(Container.DataItem,"navTitle") %></a> 9 <asp:Repeater ID="rptSub" runat="server"> 10 <HeaderTemplate> 11 <ul class="sub-nav"> 12 </HeaderTemplate> 13 <ItemTemplate> 14 <li><a href=‘<%# DataBinder.Eval(Container.DataItem,"navUrl")%>‘> 15 <%# DataBinder.Eval(Container.DataItem,"navTitle") %></a></li> 16 </ItemTemplate> 17 <FooterTemplate> 18 </ul> 19 </FooterTemplate> 20 </asp:Repeater> 21 </li> 22 </ItemTemplate> 23 </asp:Repeater> 24 </ul> 25 </div> 26 </form> 27 </body> 28 </html>
后台的实现:
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace LearnTest { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { InitData(); } } /// <summary> /// 初始化数据 /// </summary> private void InitData() { SqlConnection cn = new SqlConnection(@"server=(local);uid=sa;pwd=xjai18749695757;database=Test"); SqlDataAdapter da = new SqlDataAdapter("select * from nav where parentId = 0",cn); DataSet ds = new DataSet(); cn.Open(); //打开数据库连接 da.Fill(ds); rptNav.DataSource = ds.Tables[0].DefaultView; rptNav.DataBind(); cn.Close(); } //绑定一级菜单时绑定二级菜单 protected void rptNav_ItemDataBound(object sender, RepeaterItemEventArgs e) { //判断repeater的数据绑定列 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem) { //当前一级菜单的ID string id = ((DataRowView)(e.Item.DataItem)).Row["Id"].ToString(); //找到下面的repeater控件 Repeater rpt = (Repeater)e.Item.FindControl("rptSub"); if (rpt!=null) { SqlConnection cn = new SqlConnection(@"server=(local);uid=sa;pwd=123456;database=Test"); SqlCommand cmd = new SqlCommand("select * from nav where parentId =@parentId",cn); cmd.Parameters.Add("@parentId",SqlDbType.VarChar,11).Value = id; cn.Open(); rpt.DataSource = cmd.ExecuteReader(); rpt.DataBind(); cn.Close(); } } } } }
这就是用repeater进行嵌套来进行实现的!
标签:div htm jpg default 实现 comm close object control
原文地址:https://www.cnblogs.com/qiu18359243869/p/12749635.html