-2

我想以这种形式显示 TreeView ... 图片

    private void DatabaseToTreeView_Load(object sender, EventArgs e)
    {

        {
        String connectionString = @"String here";

            SqlConnection connection = new SqlConnection(connectionString);

            DataSet ds = new DataSet();


            connection.Open();
            SqlCommand comm = new SqlCommand("Select CourseName from Course", connection);

            SqlDataReader reader = comm.ExecuteReader();
            treeView1.Nodes.Clear();
             //Parent NODE-1
            TreeNode prntnode = new TreeNode();
            prntnode.Text = "Courses";
            prntnode.ImageIndex = 0;
            prntnode.SelectedImageIndex = 0;
            this.treeView1.Nodes.Add(prntnode);
             while (reader.Read())
            {
              prntnode.Nodes.Add(reader["CourseName"].ToString());
            }
            SqlCommand comm1 = new SqlCommand("Select BranchName from Branch INNER JOIN Course on Branch.CourseCode=Course.CourseCode", connection);
             //SqlDataReader reader1 = comm.ExecuteReader();
             // treeView1.ChildNode.Clear();

             TreeNode ChildNode = new TreeNode("BranchName");
             // ChildNode.Tag = "BranchName";
             //ChildNode.Text = "BranchName";
             ChildNode.ImageIndex = 1;
             ChildNode.SelectedImageIndex = 1;
             //treeView1.SelectedNode.Nodes.Add(ChildNode);
             prntnode.Nodes.Add(ChildNode);
             while (reader.Read())
             {
                 ChildNode.Nodes.Add(reader["BranchName"].ToString());
             }

            comm.Connection.Close();

        }
    }
4

1 回答 1

2

你应该创建Nodes. 您可以将子节点添加到父节点的 Nodes 集合中。这是一个小示例,但您必须对其进行调整:

var treeView = new TreeView();
var node = new TreeNode("Node 1 Display Name");

// if you are using entity framework or an ORM it might be helpful to add a reference to the object
node.Tag = myDataObject;
treeView.Nodes.Add(node);

我建议您从下到上构建树,因为如果您拥有所需的所有数据,它会更容易。该TreeNode类型也有一个Nodes属性。您可以使用与 with 相同的方法TreeView.Nodes

于 2013-09-17T09:28:30.020 回答