c# 菜单无限极分类-利用递归

 

表结构:

c# 菜单无限极分类-利用递归_第1张图片

前台代码:

<%@ 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);
                }
            }
        }
    }

 

你可能感兴趣的:(C#)