• “递归”实现无限级分类


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;

    public partial class _Default : System.Web.UI.Page
    {
        AccessHelper helper = new AccessHelper();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                helper.CreateCommand("select * from category");
                GridView1.DataSource = helper.ExecuteQuery();
                GridView1.DataBind();

                helper.CreateCommand("select * from category where pid=0");
                DataTable dt_topca = helper.ExecuteQuery();  // 选择所有顶级分类
                string html = "<ul>\n";
                foreach (DataRow row in dt_topca.Rows)
                {
                    html += "<li>\n";
                    html += row["caname"].ToString() + "\n";
                    AddChildCa(row["id"].ToString(), ref html); // 递归添加子分类,用ref传html字符串的地址进去
                    html += "</li>\n";
                }
                html += "</ul>\n";
                litHTML.Text = html;
            }
        }

        // 递归添加子分类,用ref传html字符串的地址进去
        private void AddChildCa(string pid, ref string html)
        {
            html += "<ul>\n";
            helper.CreateCommand("select * from category where pid=" + pid);
            DataTable dt_subca = helper.ExecuteQuery();
            foreach (DataRow row in dt_subca.Rows)
            {
                html += "<li>\n";
                html += row["caname"].ToString() + "\n";
                AddChildCa(row["id"].ToString(), ref html); // 递归添加子分类,用ref传html字符串的地址进去
                html += "</li>\n";
            }
            html += "</ul>\n";
        }
    }

    页面代码:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!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 style="font-weight: bold; color: Red;">
            数据库中的数据:
        </div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <hr />
        <div style="font-weight: bold; color: Blue;">
            递归生成HTML标记:
        </div>
        <asp:Literal ID="litHTML" runat="server"></asp:Literal>
        </form>
    </body>
    </html>

  • 相关阅读:
    17多校6 HDU
    E. Present for Vitalik the Philatelist 反演+容斥
    HDU
    F. Cowmpany Cowmpensation dp+拉格朗日插值
    hdu6088 组合数+反演+拆系数fft
    任意模数fft
    Codeforces Round #258 (Div. 2)E
    bzoj3670: [Noi2014]动物园
    HDU
    IO-InputStreamReader
  • 原文地址:https://www.cnblogs.com/kiwifruit/p/1863146.html
Copyright © 2020-2023  润新知