ASP.NET - 多级分类
表结构:
表数据:
最终效果:
前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="APManage.Test" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TreeView ID="TreeView1" runat="server"> </asp:TreeView> </div> </form> </body> </html>
后端代码:
using System; using System.Data; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace APManage { public partial class Test : System.Web.UI.Page { private readonly string ConnString = @"server = HUANGFU-PC; database = DB_APManage; integrated security = true"; private DataTable dt = null; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { dt = new DataTable(); GetMenuToDataTable("select * from Tb_APCategory", dt); BindTree(dt, null, "1000"); } } private void BindTree(DataTable dtSource, TreeNode parentNode, string parentID) { DataRow[] rows = dtSource.Select(string.Format("ParentID={0}", parentID)); foreach (DataRow row in rows) { TreeNode node = new TreeNode(); node.Text = row["CategoryName"].ToString(); node.Value = row["ParentID"].ToString(); BindTree(dtSource, node, row["ID"].ToString()); if (parentNode == null) { this.TreeView1.Nodes.Add(node); } else { parentNode.ChildNodes.Add(node); } } } private DataTable GetMenuToDataTable(string query, DataTable dt) { using (SqlConnection conn = new SqlConnection(ConnString)) { SqlCommand cmd = new SqlCommand(query, conn); SqlDataAdapter ada = new SqlDataAdapter(cmd); ada.Fill(dt); } return dt; } } }
posted on 2015-09-08 17:05 ultrastrong 阅读(960) 评论(0) 编辑 收藏 举报