现在的位置: 首页 > 综合 > 正文

treeview 实现数据的绑定

2013年05月17日 ⁄ 综合 ⁄ 共 2678字 ⁄ 字号 评论关闭
~今天网站终于上线了,心情很好,晚上特意在社区测试了好久。
每天希望都有时间来学习新的技术。
今天是treeview控件,学习开始之前懵里懵懂,以为它有多神秘,看了之后,也不过如此,
原理是 :假设是个两级的treeview,则只需为它先绑定depth=0的节点,然后根据depth=0的节点的id来绑定depth=1的节点,
原理很简单,只是一级一级的绑定
觉得要学好一门技术,要先知道它的功能和展现,所以先给个页面呈现的代码,

<asp:TreeView  ID="TreeView1" EnableClientScript="false"  runat="server" >
           
<Nodes>
               
<asp:TreeNode SelectAction="Expand" Expanded="false" PopulateOnDemand="true" Text="网站开发"></asp:TreeNode>
           
</Nodes>
        
</asp:TreeView>

里面的SelectAction属性是Expand,表示节点的选择事件是展开,PopulateOnDemand=true是表示动态的绑定数据。
数据库为


首先写个绑定数据库的方法。

    private DataSet RunQuery(string command)
    {
        
string strconn = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
        
using (SqlConnection conn = new SqlConnection(strconn))
        {
            
using (SqlCommand cmd = new SqlCommand(command, conn))
            {
                SqlDataAdapter da 
= new SqlDataAdapter(cmd);
                DataSet ds 
= new DataSet();
                da.Fill(ds);
                
return ds;
            }
        }
    }

在webconfig中设置一下就可以了,加个using system.data.sqlclient.
然后是绑定传说中最高级的节点

    private void BindParent(TreeNode node)
    {
        DataSet ds 
= RunQuery("select f_id,f_content from dbo.father");
        
if (ds.Tables.Count > 0)
        {
            
foreach (DataRow row in ds.Tables[0].Rows)
            {
                TreeNode newnode 
= new TreeNode(row["f_content"].ToString(), row["f_id"].ToString());
                    newnode.SelectAction 
= TreeNodeSelectAction.Expand;
                    newnode.PopulateOnDemand 
= true;
                    node.ChildNodes.Add(newnode);
            }
        }
    }

其次是绑定下一级的

    private void BindChild(TreeNode node)
    {
        DataSet ds 
= RunQuery("select c_content,c_id from dbo.child where c_fid= "+node.Value);
        
if (ds.Tables.Count > 0)
        {
            
foreach (DataRow row in ds.Tables[0].Rows)
            {
                TreeNode newnode 
= new TreeNode(row["c_content"].ToString(), row["c_id"].ToString());
                    newnode.SelectAction 
= TreeNodeSelectAction.Expand;
                    newnode.PopulateOnDemand 
= true;
                    node.ChildNodes.Add(newnode);
            }
        }
    }

根据上一级节点的ID绑定下一级数据。多层亦如此。
当然还差一步是要绑定数据了,也就是

         TreeView1.TreeNodePopulate+=new TreeNodeEventHandler(TreeView1_TreeNodePopulate);

protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        
switch (e.Node.Depth)
        { 
            
case 0:
                BindParent(e.Node);
                
break;
            
case 1:
                BindChild(e.
Node);
                
break;
        }
    }

然后运行生成,其实蛮简单的,是吧,运行结果如下(我写的是三层级别的),

OK,万事搞定了,一个控件学好了基础,然后可以对其慢慢扩展了,如果没有试成功的可以找我要源码。

请大家不吝赐教!!!

抱歉!评论已关闭.