动态绑定TreeVew
动态绑定TreeVew
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
private DataView dv;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
BuilderTree(-1, (TreeNode)null);
}
}
private void GetData()
{
string sql = "select * from inventoryclass";
DataSet ds = DBHelper.GetData(sql);
dv = new DataView(ds.Tables[0]);
}
//树的绑定
private void BuilderTree(int ParentID, TreeNode pNode)
{
TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
dv.RowFilter = "ParentID =" + ParentID;
foreach (DataRowView row in dv)
{
TreeNode node = new TreeNode();
if (pNode == null)
{
//添加根节点
node.Text = row["name"].ToString();
TreeView1.Nodes.Add(node);
node.Expanded = true;
BuilderTree(int.Parse(row["id"].ToString()), node); //递归
}
else
{
//添加当前节点的子节点
node.Text = row["name"].ToString();
pNode.ChildNodes.Add(node);
node.Expanded = true;
BuilderTree(int.Parse(row["id"].ToString()), node); //递归
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
///DBHelper 的摘要说明
/// </summary>
public class DBHelper
{
public DBHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
{
try
{
SqlConnection conn = new SqlConnection(@"server=(local);database=db_13;uid=sa;pwd=13875712605;");
//SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
conn.Close();
return ds;
}
catch(Exception e)
{
throw new Exception("连接错误");
}
}
}