日期:2011-08-05  浏览次数:20408 次

所做的小项目中需要多级分类, 试着学习实现多级分类。由于对存储过程本身并不大熟悉,也不想借助于treeview,于是递归逻辑采用C#实现,配合数数据库完成了多级分类的获取方法。增加分类节点应该说是比较简单的,此文暂略。

数据库表:CategoryInfo

字段名           类型

ciID                  int                        //记录序号,自增量

ciName         nvarchar(20)       //分类名

ciParent           int                       //父分类序号

ciLayer              int                      //所处的层次

ciDescription     nvarchar(200)   //对分类的描述

获取子分类的存储过程

CREATE  PROCEDURE [dbo].[category_getChild]
 @cName nvarchar(20)
AS
BEGIN
DECLARE @tmpID int
SELECT @tmpID=ciID FROM CategoryInfo
   WHERE RTRIM(ciName) = RTRIM(@cName)
if(@tmpID IS NOT NULL)
SELECT * FROM CategoryInfo
  WHERE ciParent = @tmpID
  ORDER BY ciLayer 
END

获取子分类的函数

        public IList<CategoryInfo> GetChildCategories(IList<CategoryInfo> cInfos,string cName)
        {
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("category_getChild", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter(PARAM_CNAME, SqlDbType.NVarChar, 20));
            cmd.Parameters[PARAM_CNAME].Value = cName;

            IList<string> tmpNames = new List<string>();   //临时存储获取的子
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {                  
                    while (reader.Read())
                    {
                      
                        CategoryInfo cInfo = new CategoryInfo(