C# 中遍历树 ajax读取数据 递归算法实现数据树结构输出
数据表格字段为:id,Name,pID(父级ID)
js代码
服务器端C#代码
附件为我写的测试项目
数据表格字段为:id,Name,pID(父级ID)
js代码
<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#代码
public DataTable GetChildren(int id)
{
[img]http://dl.iteye.com/upload/attachment/0066/5386/b847b4aa-7d65-33f0-aa03-2fe8337c943d.jpg[/img]
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];
}
}
}
附件为我写的测试项目