using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Left : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindTree();
//InitTree();
}
}
#region 主从表绑定
private void BindTree()
{
DataSet dst = GetTreeViewData();
TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
foreach (DataRow masterRow in dst.Tables["province"].Rows)
{
TreeNode masterNode = new TreeNode((string)masterRow["province"]);
TreeView1.Nodes.Add(masterNode);
foreach (DataRow childRow in masterRow.GetChildRows("Children"))
{
TreeNode childNode =new TreeNode((string)childRow["city"]);
masterNode.Expanded = false;
masterNode.ChildNodes.Add(childNode);
}
}
}
private DataSet GetTreeViewData()
{
string constring = System.Configuration.ConfigurationSettings.AppSettings["ConnectionStr"];
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter daprovince = new SqlDataAdapter("SELECT * FROM province", con);
SqlDataAdapter dacity = new SqlDataAdapter("SELECT * FROM city", con);
DataSet ds = new DataSet();
daprovince.Fill(ds, "province");
dacity.Fill(ds, "city");
ds.Relations.Add("Children", ds.Tables["province"].Columns["provinceid"], ds.Tables["city"].Columns["father"]);
return ds;
}
#endregion
#region 递归绑定同一个表数据
private void InitTree()
{
DataTable dt = GetTreeViewTable();
DataView dv = new DataView(dt);
dv.RowFilter = "ParentID=0";
TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
foreach (DataRowView drv in dv)
{
TreeNode node = new TreeNode();
node.Text = drv["text"].ToString();
node.Value = drv["ID"].ToString();
node.Expanded = false;
TreeView1.Nodes.Add(node);
AddReplies(dt,node);
}
}
private DataTable GetTreeViewTable()
{
string constring = System.Configuration.ConfigurationSettings.AppSettings["ConnectionStr"];
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM treeview", con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
private void AddReplies(DataTable dt, TreeNode node)
{
DataView dv = new DataView(dt);
dv.RowFilter = "ParentID='" + node.Value + "'";
foreach (DataRowView row in dv)
{
TreeNode replyNode = new TreeNode();
replyNode.Text = row["text"].ToString();
replyNode.Value = row["ID"].ToString();
replyNode.Expanded = false;
node.ChildNodes.Add(replyNode);
AddReplies(dt,replyNode);
}
}
#endregion
}
|
|