using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;
public partial class tree : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTree();
}
}
private void BindTree()
{
string conStr = ConfigurationManager.AppSettings["ConnectionString"];
string sqlstr = "SELECT * FROM BigCategories LEFT JOIN SmallCategories ON BigCategories.OneID=SmallCategories.OneID";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conStr);
DataSet ds = new DataSet();
da.Fill(ds, "tree");
DataTable dt = ds.Tables["tree"];
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
//值
tn.Value = dr["OneID"].ToString();
//显示的文本
tn.Text = dr["BigCate"].ToString();
//节点是否存在,存在就等于它
if (this.TreeView1.FindNode(dr["OneID"].ToString()) != null)
{
tn = this.TreeView1.FindNode(dr["OneID"].ToString());
}
//不存在就添加
else
{
this.TreeView1.Nodes.Add(tn);
}
//添加子节点
if (!Convert.IsDBNull(dr["Small_Cate"]))
{
TreeNode child = new TreeNode();
child.Text = dr["Small_Cate"].ToString();
child.NavigateUrl = "?id=" + dr["ID"].ToString();
tn.ChildNodes.Add(child);
}
}
}
}
if (!IsPostBack)
{
DataView dv = sqlhelper.executeDataTable("select * from Tom").DefaultView;
foreach (DataRowView dataRow in dv)
{
TreeNode tn = new TreeNode();
tn.Text = dataRow["name"].ToString();
tn.Value = dataRow["id"].ToString();
tn.NavigateUrl = "Product.aspx?typeid=0&id=" + dataRow["id"].ToString() + "";
//设定树是否展开
tn.Expanded = false;
TreeView1.Nodes.Add(tn);
addNodes(tn);
}
}
}
private void addNodes(TreeNode tn)
{
int id = Convert.ToInt32(tn.Value);
DataView dv = sqlhelper.executeDataTable("select * from ProName where TomId=" + id).DefaultView ;
foreach (DataRowView dataRow in dv)
{
TreeNode ctn = new TreeNode();
ctn.Text = dataRow["ProType"].ToString();
ctn.NavigateUrl = "Product.aspx?typeid="+dataRow["id"].ToString()+"&id=" + dataRow["TomId"].ToString() + "";
tn.ChildNodes.Add(ctn);
}
}