首先在界面上放一个TreeView控件。
<asp:treeview ID="Treeview1" runat="server">
</asp:treeview>
编写递归方法
public void BuildTreeNode(string parentid, TreeNode tn,DataTable dtParam)//dtParam为所有的表信息,无需筛选。
{
DataTable currTable = new DataTable();
currTable = dtParam.Clone();
DataTable nextTable = new DataTable();
nextTable = dtParam.Clone();
for (int i = 0; i < dtParam.Rows.Count; i++)
{
if (dtParam.Rows[i][1].ToString() == parentid)
{
currTable.Rows.Add(dtParam.Rows[i].ItemArray);
}
else
{
nextTable.Rows.Add(dtParam.Rows[i].ItemArray);
}
}
for (int j = 0; j <currTable.Rows.Count; j++)
{
DataRow dr = currTable.Rows[j];
TreeNode mytn = new TreeNode();
mytn.Text = dr[2].ToString();
mytn.Value = dr[0].ToString();
BuildTreeNode(dr[0].ToString(), mytn, nextTable);
if (tn == null)
{
Treeview1.Nodes.Add(mytn);
}
else
{
tn.ChildNodes.Add(mytn);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dtParam = GetAllDeptInfo();
TreeNode tn = null;
BuildTreeNode("0", tn, dtParam);
Treeview1.DataSource = tn;
DropDownList1.DataSource = dtTree;
Treeview1.DataBind();
}
}