从数据库显示Treeview在表单加载和添加子,子Childs ...?

时间:2013-09-17 09:18:41

标签: c# treeview

我想在此表单中显示TreeView ... Image

    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();

        }
    }

1 个答案:

答案 0 :(得分:2)

您应该创建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属性。您可以使用与TreeView.Nodes相同的方法。