The first is the design of the data table
Where Treeid refers to the parent ID of the menu item, If the Treeid is 0. Indicates that the menu item is a root menu item, otherwise, he is a submenu of a menu item, such as an item with an ID of 2, and his parent node is 1. Then he is the John submenu, and John is the root menu, position is used only for root menu items to control the order of display.
Drag a menu control into the Web page and add code
Copy Code code as follows:
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 is the database name
Set Database Operation command
CN. Open ();
SqlCommand scmd = new SqlCommand ("SELECT * from Tb_menu where treeid=0 order by position", CN); Select the root menu
SqlDataReader ODR = Scmd.executereader ();
while (ODR. Read ())//cyclic reading
{
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); Add to root Menu
Treeid = Convert.ToInt16 (odr["id"). ToString ());
Addchildmenu (Menunode);
}
To close a database connection
Scmd.Connection.Close ();
}
protected void Addchildmenu (MenuItem pnode)//Add submenu
{
SqlConnection CN = new SqlConnection ("server=.; Trusted_connection=sspi;database=menudb ");
?
Set Database Operation command
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); Add a submenu to the current menu item
Treeid = Convert.ToInt16 (odr["id"). ToString ());
Addchildmenu (Menunode); Looping add submenus
}
To close a database connection
Scmd1.Connection.Close ();
}
}
The final effect is the following figure