First, data table Design
TreeId indicates the parent ID of the menu item. If treeId is 0. indicates that this menu item is a single root menu item. Otherwise, it indicates that it is a sub-menu of a menu item. For example, if the item id is 2, its parent node is 1. then he is the sub-menu of Michael Jacob, while Michael Jacob is the root menu. position is only used for single root menu items and used to control the display sequence.
Drag a menu control into the webpage and add code
Copy codeThe Code is 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 commands
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 () // Read cyclically
{
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 the root menu
TreeID = Convert. ToInt16 (odr ["id"]. ToString ());
Addchildmenu (menuNode );
}
// Close the database connection
Scmd. Connection. Close ();
}
Protected void addchildmenu (MenuItem pnode) // Add sub menu
{
SqlConnection CN = new SqlConnection ("server =.; Trusted_Connection = SSPI; database = MENUDB ");
?
// Set database operation commands
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 sub-menu for the current menu item
TreeID = Convert. ToInt16 (odr ["id"]. ToString ());
Addchildmenu (menuNode); // Add sub menu cyclically
}
// Close the database connection
Scmd1.Connection. Close ();
}
}
The final result is as follows: