我想在此表单中显示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();
}
}
答案 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
相同的方法。