我从数据库里读取数据如
select ID,ClassName,ParentID from tb_ClassID,编号
ClassName 类别名
ParentID 是所属类别比如
ID ClassName ParentID
1 A 0
2 B 0
3 AA 1
4 aa 3
5 aaa 4怎么样读取才能绑定在TreeView上
高分求助
select ID,ClassName,ParentID from tb_ClassID,编号
ClassName 类别名
ParentID 是所属类别比如
ID ClassName ParentID
1 A 0
2 B 0
3 AA 1
4 aa 3
5 aaa 4怎么样读取才能绑定在TreeView上
高分求助
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Data.SqlClient;public partial class LeftPage : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BBSConnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
try
{
string sql = "select * from tb_Class where ParentID='0' order by ParentID";
con.Open();
SqlCommand com = new SqlCommand(sql, con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sda.Fill(ds);
this.TreeView1.Nodes.Clear();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode RootNode = new TreeNode(ds.Tables[0].Rows[i]["ClassName"].ToString(), ds.Tables[0].Rows[i]["ID"].ToString());
this.TreeView1.Nodes.Add(RootNode);
BuildNode((int)ds.Tables[0].Rows[i]["ID"], RootNode);
}
}
catch (Exception)
{
}
} private void BuildNode(int id, TreeNode node)
{
string sql = string.Format("select * from tb_Class where ParentID='{0}' order by ParentID", id);
SqlCommand com = new SqlCommand(sql, con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode ChildNode = new TreeNode(ds.Tables[0].Rows[i]["ClassName"].ToString(), ds.Tables[0].Rows[i]["ID"].ToString());
node.ChildNodes.Add(ChildNode);
BuildNode((int)ds.Tables[0].Rows[i]["ID"], ChildNode);
}
}
}
{
if (!IsPostBack)
{
DataTable();
Bind_Tree(0, null);
}
}
public void Bind_Tree(int parentID, TreeNode NODE)
{
DataView dv = new DataView((ViewState["Table"] as DataTable));
dv.RowFilter = "ParentID=" + parentID + "";
foreach (DataRowView row in dv)
{
TreeNode node = new TreeNode();
if (NODE == null)
{
node.Text = row["ClassName"].ToString();
node.Value = row["ID"].ToString();
TreeView1.Nodes.Add(node);
Bind_Tree((int)row["ID"], node);
}
else
{
node.Text = row["ClassName"].ToString();
node.Value = row["ID"].ToString();
NODE.ChildNodes.Add(node);
Bind_Tree((int)row["ID"], node);
}
}
}
public void DataTable()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
conn.Open();
string strSql = "select * from ceshi order by ParentID";
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
DataTable dt = new DataTable();
da.Fill(dt);
ViewState["Table"] = dt;
}
}