“递归”实现无限级分类

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>

posted @ 2010-10-28 09:29  大奇异果  阅读(329)  评论(0编辑  收藏  举报
Copyright ?2010 大奇异果 Contact QQ:408676935 E-mail:jialeifei@163.com