protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindTreeView(TreeView1);
}
}
private void BindTreeView(TreeView treeview)
{
//string sql = "select * from T_ZSD where course_id="+Session["Course_id"].ToString();
string sql = "select * from T_ZSD where course_id=13";
DataSet ds = DbHelperSQL.Query(sql);
DataTable dt = ds.Tables[0];
treeview.Nodes.Clear();
//创建根节点
DataRow[] parentrow = dt.Select("parentid=0");
TreeNode rootnode = new TreeNode();
rootnode.Text = parentrow[0][2].ToString() ;
rootnode.Value = parentrow[0][0].ToString();//主键的值
rootnode.Expanded = true;
rootnode.Selected = true;
treeview.Nodes.Add(rootnode);
CreateChildNode(rootnode,dt);
}
private void CreateChildNode(TreeNode parentNode,DataTable datatable)
{
DataRow[] rowlist = datatable.Select("parentid="+parentNode.Value);
foreach (DataRow row in rowlist)
{
//创建新节点
TreeNode node = new TreeNode();
node.Value = row["PK_ZSD"].ToString();
node.Text = row["zsd_name"].ToString();
node.Expanded = true;
parentNode.ChildNodes.Add(node);
CreateChildNode(node, datatable); //递归调用,寻找自身的子节点
}
}