转自:http://www.iteye.com/topic/1122691

C# 中遍历树 ajax读取数据 递归算法实现数据树结构输出 

数据表格字段为:id,Name,pID(父级ID) 
js代码 
Javascript代码
<script language="javascript" type="text/javascript">
    
    var htmlStr=new Array();
    $(function(){
    loadNode(0);
    })
    
    function loadNode(pid)
    {
        var vDtbl=_Default.GetChildren(pid).value;
        if(vDtbl!=null)
        {
            for (var i = 0; i < vDtbl.Rows.length; i++) {  
                    var NodeID = vDtbl.Rows[i]["id"];
                    var NodeName=vDtbl.Rows[i]["Name"];
                    var PID=vDtbl.Rows[i]["pID"];

                    htmlStr.push("<ul>");
                    htmlStr.push("<li id='"+NodeID+"'>");htmlStr.push(NodeName);htmlStr.push("</li>");

                    if(vDtbl.Rows.length!=0)// 判断该NodeID是否存在子集
                    {
                    loadNode(NodeID);
                    }
                    htmlStr.push("</ul>");
                    }// end for
        var htmlcode="";
        htmlcode=htmlStr.join("");             
        $("#loadNode").html(htmlcode);             

        } 
    }
    </script>
服务器端C#代码 
C#代码
    public DataTable GetChildren(int id)
    {
        //string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SiteConnectionString"].ConnectionString;
        //string strCon = "Data Source=.;Integrated Security=SSPI;Initial Catalog=test";
        string strCon = "server=.;database=test;Integrated Security=sspi";
        using (SqlConnection conn = new SqlConnection(strCon))
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "select  id, Name,pID from tab_Tree where pID=" + id;
                conn.Open();
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter dbA = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                dbA.Fill(ds);
                conn.Close();
                return ds.Tables[0];
            }
        }
    }

附件为我写的测试项目


  • 大小: 5.9 KB




本文转载:CSDN博客