使用asp.net递归的方法来实现treeview的数据绑定

        递归我想大家都还是比较熟悉吧,在asp.net当中递归也可以实现很多的效果,那么今天的编程软件教程就为你演示一下使用asp.net递归的方法来实现treeview的数据绑定数据。

   public partial class Site : System.Web.UI.MasterPage
    {
        private DataSet ds;
        private DataSet set;
        private SqlConnection conn;
        private SqlDataAdapter dat;
        private string sql = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindTreeView();
            }
        }
        /// <summary>
        /// 实现treeview绑定的方法
        /// </summary>
        /// <param name="ParentID">类型编号</param>
        /// <param name="Item">节点对象</param>
///编程软件教程    
        public void BindTreeView()
        {
            TreeNode node;
            TreeNode nodes;
            ds = RunQuery("select * from bookCagetory");
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                node = new TreeNode()
                {
                    Text = item["categoryName"].ToString(),
                    Value = item["categoryID"].ToString()
                };
                sql = string.Format("select * from Book where categoryID={0}", int.Parse(item["categoryID"].ToString()));
                set = RunQuery(sql);
                foreach (DataRow row in set.Tables[0].Rows)
                {
                    nodes = new TreeNode()
                    {
                        Text = row["bookTitle"].ToString(),
                        Value = row["bookid"].ToString()
                    };
                    node.ChildNodes.Add(nodes);
                }
                TreeViews.BorderWidth = 0;
                TreeViews.BorderStyle = BorderStyle.None;
                TreeViews.Nodes.Add(node);
            }
        }
        /// <summary>
        /// 实现数据库查询的方法
        /// </summary>
        /// <param name="sql">查询的sql语句</param>
        /// <returns></returns>
        public DataSet RunQuery(string sql)
        {
            conn = new SqlConnection("server=.;uid=sa;pwd=123456;database=Chapter4");
            dat = new SqlDataAdapter(sql, conn);
            ds = new DataSet();
            dat.Fill(ds);
            return ds;
        }

        protected void TreeViews_SelectedNodeChanged(object sender, EventArgs e)
        {
            int index = int.Parse(TreeViews.SelectedValue);
            string str = TreeViews.SelectedNode.Text;
            Response.Redirect(string.Format("Demo.aspx?Index={0}&&Str={1}",index,str));
        }
    }
}

教程的代码来自:http://korey.blog.51cto.com/

本文出自 “编程软件教程|软件破解..” 博客,谢绝转载!

你可能感兴趣的:(数据,职场,asp.net,休闲)