TreeView

来源:互联网 发布:开手机淘宝店要多少钱 编辑:程序博客网 时间:2024/05/18 21:49

 类库:

public class DB
{
    SqlConnection con = null;
    SqlCommand cmd = new SqlCommand();
    public DB()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
        con = new SqlConnection("Data Source=WIN-DJD89O16MSM\\SQLEXPRESS;Initial Catalog=vote;Integrated Security=True;");

    }
    public SqlConnection getCon()
    {
       
        if(con.State==ConnectionState.Closed)
        con.Open();
        return con;

    }

    public void clear()
    {

        if (con.State == ConnectionState.Open)
            con.Close();

    }

 

       public DataSet getds(string sqlsel)
    {
        cmd.Connection = getCon();
        cmd.CommandText = sqlsel;
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;

    }
}

 

显示TreeView控件的后台代码:

 protected void Page_Load(object sender, EventArgs e)
    {
       // AddTree(0, (TreeNode)null);

        //由于这句话的存在,每次点一下页面其他控件,就会新出现一个TreeView

                                                          //所以这里还要改一下!


        if (!IsPostBack)
        {
            AddTree(0, (TreeNode)null);
        }

    }

 

public void AddTree(int ParentID, TreeNode pNode)
    {
        DB db = new DB();
        string sql="select * from tbTree";
        DataSet ds= db.getds(sql);
        TreeNode tn1 = new TreeNode();
        DataView dvTree = new DataView(ds.Tables[0]);
        //过滤ParentID,得到当前的所有子节点
        dvTree.RowFilter = "[PARENTID] = " + ParentID;
        foreach (DataRowView Row in dvTree)
        {
            if (pNode == null)
            {    //添加根节点
                tn1.Text = Row["ConText"].ToString();
                tn1.Value = Row["ID"].ToString();
                TreeView2.Nodes.Add(tn1);
                tn1.Expanded = false;
                AddTree(Convert.ToInt32(Row["ID"].ToString()), tn1);
              //与上面等效  AddTree(Int32.Parse(Row["ID"].ToString()), tn1);    //再次递归
            }
            else
            {   //添加当前节点的子节点
                TreeNode tn2 = new TreeNode();
                tn2.Text = Row["ConText"].ToString();
                tn2.Value = Row["ID"].ToString();
                //tn2.NavigateUrl = "javascript:alert('" + Row["ID"].ToString() + "');";
                //tn2.ShowCheckBox = true;
                pNode.ChildNodes.Add(tn2);
                tn1.Expanded=false;

                AddTree(Convert.ToInt32(Row["ID"].ToString()), tn2);
             //   AddTree(Int32.Parse(Row["ID"].ToString()), tn2);    //再次递归
            }

        }
    }

以上代码参考自http://qwzhl100.blog.163.com/blog/static/21331242009588197359/
原创粉丝点击