用户控件-TreeView的用法
好闲话少说
由于是用户控件所以把 treeview的部分属性和事件公共,方便用此控件的页面调用
页面 TreeDept.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TreeDept.ascx.cs" Inherits="UserControls_TreeDept" %>
<asp:TreeView ID="TreeView1" runat="server" ExpandDepth="1" ImageSet="Contacts"
NodeIndent="10" onselectednodechanged="TreeView1_SelectedNodeChanged"
ontreenodepopulate="TreeView1_TreeNodePopulate" Width="101px">
<ParentNodeStyle Font-Bold="True" ForeColor="#5555DD" />
<HoverNodeStyle Font-Underline="False" />
<SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px"
VerticalPadding="0px" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black"
HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
</asp:TreeView>
TreeDept.ascx.CS
public partial class UserControls_TreeDept : System.Web.UI.UserControl
{
public event EventHandler DeptSel;
public string DeptSelectNodeText
{
get { return TreeView1.SelectedNode.Text; }
}
SqlConnection con = new SqlConnection(@"server=LT-C9A4FDA64461;uid=sa;pwd=sa;database=ltweb");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTree();
}
}
void BindTree()
{
TreeNode tn = new TreeNode();
tn.Text = "软件";
tn.Value = "1";
tn.PopulateOnDemand = true;
TreeView1.Nodes.Add(tn);
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from dept where parentID="+int.Parse(e.Node.Value),con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode(dr["Dept_Name"].ToString(), dr["Dept_ID"].ToString());
tn.PopulateOnDemand = true;
e.Node.ChildNodes.Add(tn);
}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
if(DeptSel!=null)
DeptSel(this,EventArgs.Empty);
}
}
<form id="form1" runat="server">
<div>
<uc1:TreeDept ID="TreeDept1" runat="server" OnDeptSel="DeptSel_Change"/>
</div>
</form>
后台
public partial class Dept : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DeptSel_Change(object sender, EventArgs e)
{
Response.Write(TreeDept1.DeptSelectNodeText);
}
}