65.9K
CodeProject 正在变化。 阅读更多。
Home

动态绑定TreeView控件的值

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL

1分钟阅读

viewsIcon

9474

首先创建两个表:ParentTable 和 ChildTable。ParentTable -> ParentId 作为主键 -> ParentName。ChildTable -> ParentId 作为来自 ParentTable 的外键。

首先创建两个表 ParentTable 和 ChildTable

ParentTable

-->ParentId 作为主键

-->ParentName

ChildTable

-->ParentId 作为来自 ParentTable 的外键

-->ChildName

-----------------------------------------------------------------------

创建 Url SqlConnection...

然后使用此函数填充 TreeView 控件


public void fill_Tree()
{
        try
        {
            TreeView1.Nodes.Clear();
            if (con.State == ConnectionState.Closed)
                con.Open();

            SqlCommand SqlCmd = new SqlCommand("Select * from ParentTable", con);
            SqlDataReader Sdr = SqlCmd.ExecuteReader();

            SqlCmd.Dispose();


            string[,] ParentNode = new string[100, 2];

            int count = 0;

            while (Sdr.Read())
            {
                ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("ParentID")).ToString();
                ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("ParentName")).ToString();
            }

            Sdr.Close();


            for (int loop = 0; loop < count; loop++)
            {
                TreeNode root = new TreeNode();

                root.Text = ParentNode[loop, 1];
                root.Target = "_blank";
                root.NavigateUrl = "ParentPage.aspx?NodeName=" + root.Text + "";


                SqlCommand Module_SqlCmd = new SqlCommand("Select * from ChildTable where ParentId =" + ParentNode[loop, 0], con);
                SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();

                while (Module_Sdr.Read())
                {
                    TreeNode child = new TreeNode();

                    child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString();
                    child.Target = "_blank";
                    child.NavigateUrl = "ChildPage.aspx?NodeName=" + child.Text + "";

                    root.ChildNodes.Add(child);
                }

                Module_Sdr.Close();

                TreeView1.Nodes.Add(root);
            }


            TreeView1.ExpandAll();
            con.Close();
        }
        catch (Exception ex)
        {
            this.ErrorState = true;
            this.ErrorMsg = ex.Message;
        }
}

protected void Page_Load(object sender, EventArgs e)
{
        if (!IsPostBack == true)
        {
            fill_Tree();
        }
}

© . All rights reserved.