表结构:
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="RightDGExercise.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TreeView ID="TreeView1" runat="server"> </asp:TreeView> </div> </form> </body> </html>
后台代码:
public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string sql = "SELECT * FROM Menus ORDER BY Sort"; DataSet ds = MySqlHelper.ExecuteDataset(MySqlHelper.ConnectionString, System.Data.CommandType.Text, sql); if (ds.Tables != null && ds.Tables.Count > 0) { TreeNode nodeOne = new TreeNode("",""); TreeView1.Nodes.Add(nodeOne); FillTree(nodeOne,"0", ds.Tables[0]); } } } // 递归算法 private void FillTree(TreeNode treeNode,string ParentId,DataTable dt) { DataRow[] drs = dt.Select(" ParentID='"+ParentId+"'"); if (drs == null || drs.Length < 0) { return; } else { for (int i = 0; i < drs.Length; i++) { DataRow dr = drs[i]; TreeNode nodeName = new TreeNode(dr["Name"].ToString(), dr["ID"].ToString()); treeNode.ChildNodes.Add(nodeName); FillTree(nodeName, dr["ID"].ToString(), dt); } } } }
来源:https://www.cnblogs.com/honghong75042/p/3468757.html