首先是數據表的設計
其中treeId指的是該菜單項的父ID,如果treeId為0.表示該菜單項為根菜單項,否則表示他為某菜單項的子菜單,比如id為2的項,他的父節點是1.則他是張三的子菜單,而張三是根菜單,position只用於根菜單項,用於控制顯示的順序。
往網頁裡拖入一個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是數據庫名
//設定數據庫操作命令
CN.Open();
SqlCommand Scmd = new SqlCommand("select * from TB_MENU where treeId=0 order by position", CN); //選出根菜單
SqlDataReader odr = Scmd.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();
Menu1.Items.Add(menuNode); //添加到根菜單
treeID = Convert.ToInt16(odr["id"].ToString());
addchildmenu(menuNode);
}
//關閉數據庫連接
Scmd.Connection.Close();
}
protected void addchildmenu(MenuItem pnode) //添加子菜單
{
SqlConnection CN = new SqlConnection("server=.;Trusted_Connection=SSPI;database=MENUDB");
?
//設定數據庫操作命令
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); //為當前菜單項添加子菜單
treeID = Convert.ToInt16(odr["id"].ToString());
addchildmenu(menuNode); //循環添加子菜單
}
//關閉數據庫連接
Scmd1.Connection.Close();
}
}
最終效果如下圖