C#树形递归实现
数据据库结构:
id subjectname parentid
C#实现代码:
StringBuilder html = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = getTable("SELECT [Id],[subjectname],[ParentId] FROM [FileTree]");
if (dt.Rows.Count >0)
{
DataRow [] dr=dt.Select("parentid=0");
for (int i = 0; i < dr.Length; i++)
{
//html.Append(dr[i]["subjectname"] + dr[i]["id"].ToString() + "<");
html.Append(dr[i]["subjectname"] + dr[i]["id"].ToString() + " ");
CreateChildNode(dr[i]["id"].ToString(), dt);
//html.Append();
}
}
Response.Write(html.ToString());
}
private void CreateChildNode(string parentNode, DataTable dt)//创建孩子节点
{
DataRow[] rows = dt.Select("parentid=" + parentNode);//获取父亲节点下面的所有子节点
for (int i =0; i<rows.Length; i++)
{
//int FindParent = html.ToString().IndexOf(rows[i]["parentid"].ToString());
//if (FindParent > 0)
if (rows[i]["parentid"].ToString() == parentNode)
{
//html.Insert(html.ToString().IndexOf('<', FindParent), " " + rows[i]["id"].ToString() + rows[i]["subjectname"].ToString() + rows[i]["parentid"].ToString() + " ");
html.Append(" " + rows[i]["id"].ToString() + rows[i]["subjectname"].ToString() + rows[i]["parentid"].ToString() + " ");
}
CreateChildNode(rows[i]["id"].ToString(), dt);//递归调用添加孩子函数
}
}
private void CreateChildNodeDESC(string parentNode, DataTable dt)//创建孩子节点,倒序
{
DataRow[] rows = dt.Select("parentid=" + parentNode);//获取父亲节点下面的所有子节点
for (int i=rows.Length-1; i>=0;i--)
{
//int FindParent = html.ToString().IndexOf(rows[i]["parentid"].ToString());
//if (FindParent > 0)
if (rows[i]["parentid"].ToString() == parentNode)
{
//html.Insert(html.ToString().IndexOf('<', FindParent), " " + rows[i]["id"].ToString() + rows[i]["subjectname"].ToString() + rows[i]["parentid"].ToString() + " ");
html.Append(" " + rows[i]["id"].ToString() + rows[i]["subjectname"].ToString() + rows[i]["parentid"].ToString() + " ");
}
CreateChildNode(rows[i]["id"].ToString(), dt);//递归调用添加孩子函数
}
}
public DataTable getTable(string sql)//查询数据,返回表
{
string sqlstring = "Data Source=192.168.1.6;Initial Catalog=BankAds;User ID=sa;Password=111";
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
SqlCommand com = new SqlCommand(sql,conn);
SqlDataAdapter sda = new SqlDataAdapter();
DataTable dt=new DataTable();
sda.SelectCommand = com;
sda.Fill(dt);
conn.Close();
return dt;
}