首先是數(shù)據(jù)表的設(shè)計
其中treeId指的是該菜單項的父ID,如果treeId為0.表示該菜單項為根菜單項,否則表示他為某菜單項的子菜單,比如id為2的項,他的父節(jié)點是1.則他是張三的子菜單,而張三是根菜單,position只用于根菜單項,用于控制顯示的順序。
往網(wǎng)頁里拖入一個menu控件,然后添加代碼
代碼如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.ProviderBase;
public partial class _Default : System.Web.UI.Page
{
public int treeID;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection CN = new SqlConnection("server=.;Trusted_Connection=SSPI;database=MENUDB"); //MENUDB是數(shù)據(jù)庫名
//設(shè)定數(shù)據(jù)庫操作命令
CN.Open();
SqlCommand Scmd = new SqlCommand("select * from TB_MENU where treeId=0 order by position", CN); //選出根菜單
SqlDataReader odr = Scmd.ExecuteReader();
while (odr.Read()) //循環(huán)讀取
{
MenuItem menuNode = new MenuItem();
menuNode.Text = odr["names"].ToString();
menuNode.Value = odr["id"].ToString();
menuNode.Enabled = true;
menuNode.NavigateUrl = odr["page"].ToString();
Menu1.Items.Add(menuNode); //添加到根菜單
treeID = Convert.ToInt16(odr["id"].ToString());
addchildmenu(menuNode);
}
//關(guān)閉數(shù)據(jù)庫連接
Scmd.Connection.Close();
}
protected void addchildmenu(MenuItem pnode) //添加子菜單
{
SqlConnection CN = new SqlConnection("server=.;Trusted_Connection=SSPI;database=MENUDB");
?
//設(shè)定數(shù)據(jù)庫操作命令
CN.Open();
SqlCommand Scmd1 = new SqlCommand("select * from TB_MENU where treeID=" + treeID + "", CN);
?
SqlDataReader odr = Scmd1.ExecuteReader();
while (odr.Read())
{
MenuItem menuNode = new MenuItem();
menuNode.Text = odr["names"].ToString();
menuNode.Value = odr["id"].ToString();
menuNode.Enabled = true;
menuNode.NavigateUrl = odr["page"].ToString();
pnode.ChildItems.Add(menuNode); //為當(dāng)前菜單項添加子菜單
treeID = Convert.ToInt16(odr["id"].ToString());
addchildmenu(menuNode); //循環(huán)添加子菜單
}
//關(guān)閉數(shù)據(jù)庫連接
Scmd1.Connection.Close();
}
}
最終效果如下圖
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com