asp.net Menu控件+SQLServer实现动态多级菜单
首先是数据表的设计
其中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();
}
}
最终效果如下图