数据库动态添加treeview的节点
数据表:deptTree
deptId int
deptName nvchar
parentId int
nodeValue nvchar
代码部分:
private DataView dvDept = null;
private DataView dvMember = null;protected void Page_Load(object sender, EventArgs e)
{
CreateTable();
AddTree(-1, (TreeNode)null);
}
private void CreateTable()
{
try
{
OleDbConnection con = DataBase.Con;
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
//cmd.CommandText = "select department.departmentId,department.departmentName,managerId,department.higherDepartmentId,member.memberId,member.name from department,member where department.departmentId=member.departmentId ";
cmd.CommandText = "select * from deptTree";
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "deptTree");
dvDept = ds.Tables["deptTree"].DefaultView;
con.Close();
OleDbConnection co = DataBase.Con;
OleDbCommand cm = new OleDbCommand();
cm.Connection = co;
//cmd.CommandText = "select department.departmentId,department.departmentName,managerId,department.higherDepartmentId,member.memberId,member.name from department,member where department.departmentId=member.departmentId ";
cm.CommandText = "select departmentId,memberId,name from member order by departmentId";
OleDbDataAdapter daa = new OleDbDataAdapter();
daa.SelectCommand = cm;
DataSet dss = new DataSet();
daa.Fill(dss, "dvMember");
dvMember = dss.Tables["dvMember"].DefaultView;
co.Close();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}
}
public void AddTree(int parentId, TreeNode pNode)
{
dvDept.RowFilter = "parentId=" + parentId;
foreach (DataRowView row in dvDept)
{
TreeNode Node = new TreeNode();
if (pNode == null) //当节点的父节点为空,则添加当前节点为根节点
{
Node.Text = row["deptName"].ToString() ;
Node.Value = row["nodeValue"].ToString();
TreeView1.Nodes.Add(Node);
Node.Expanded = true;
AddTree(Int32.Parse(row["deptId"].ToString()), Node); //再次递归
}
else
{
//添加当前节点的子节点
Node.Text = "<a href='#' onDblClick=\"abc('" + row["nodeValue"].ToString() + "','" + row["deptName"].ToString() + "')\">" + row["deptName"].ToString() + "</a>";
Node.Value = row["nodeValue"].ToString();
pNode.ChildNodes.Add(Node);
Node.Expanded = true; //节点状态展开
AddTree(Int32.Parse(row["deptId"].ToString()), Node); //再次递归
}
}
}