转自:http://blog.sina.com.cn/s/blog_8944756d01016yaj.html
前台:
<asp:View ID="view0" runat="server">
<asp:TreeView ID="treeLanMu" runat="server" ImageSet="Arrows"
onselectednodechanged="treeLanMu_SelectedNodeChanged" >
</asp:TreeView>
</asp:View>
后台:
/// <summary>
/// 递归绑定子节点
/// </summary>
/// <param name="dt">作为数据源的DataTable</param>
/// <param name="tnc">该节点的子节点集合</param>
/// <param name="pid_val">该节点的父节点值</param>
/// <param name="id_Name">DataTable中id字段的名称</param>
/// <param name="pid_Name">DataTable中父id字段的名称</param>
/// <param name="text_Name">DataTable中name字段的名称</param>
private void BindTreeView(DataTable dt, TreeNodeCollection tnc, string pid_val, string id_Name, string pid_Name, string text_Name)
{
dt = GetAllLanmu();
DataView dv = new DataView(dt);//将DataTable存到DataView中,以便于筛选数据
TreeNode tn;//建立TreeView的节点(TreeNode),以便将取出的数据添加到节点中
//以下为三元运算符,如果父id为空,则为构建“父id字段 is null”的查询条件,否则构建“父id字段=父id字段值”的查询条件
string filter = string.IsNullOrEmpty(pid_val) ? pid_Name + " is null" : string.Format(pid_Name + "='{0}'", pid_val);
dv.RowFilter = filter;//利用DataView将数据进行筛选,选出相同 父id值 的数据
foreach (DataRowView drv in dv)
{
tn = new TreeNode();//建立一个新节点
tn.Value = drv[id_Name].ToString();//节点的Value值,一般为数据库的id值
tn.Text = drv[text_Name].ToString();//节点的Text,节点的文本显示
tnc.Add(tn);//将该节点加入到TreeNodeCollection(节点集合)中
BindTreeView(dt, tn.ChildNodes, tn.Value, id_Name, pid_Name, text_Name);//递归(反复调用这个方法,直到把数据取完为止)
}
}
调用:
DataTable dtGetN = db.GetAllLanmu();
BindTreeView(dtGetN, treeLanMu.Nodes, null, "lindex", "parentindex", "lname");
treeLanMu.ExpandAll();
另一种方法:
private void BindTreeView()
{
treeLanMu.Nodes.Clear();
DataTable dtpindex = db.GetAllByParentIndex("-1");
TreeNode unitNode = new TreeNode();
if (dtpindex.Rows.Count!=0)
{
for (int i = 0; i < dtpindex.Rows.Count; i++)
{
string Pname = dtpindex.Rows[i]["lname"].ToString();
unitNode.Text = Pname;
treeLanMu.Nodes.Add(unitNode);
BindDepartmentTree(dtpindex.Rows[i]["lindex"].ToString(), unitNode);
}
}
}
private void BindDepartmentTree(string parentId, TreeNode node)
{
DataTable dt = db.GetAllByParentIndex(parentId);
for (int i = 0; i < dt.Rows.Count; i++)
{
string id = dt.Rows[i]["lindex"].ToString();
string name = dt.Rows[i]["lname"].ToString();
TreeNode snode = new TreeNode(name);
snode.Value = id;
node.ChildNodes.Add(snode);
BindDepartmentTree(id, snode);
}
}