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

寵の児 提交于 2019-12-25 18:51:55

 

表结构:

前台代码:

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!