I have a开发者_JS百科 column in a database table which contains the filepath for each file in the table. How can I make a treeview in c# which will mimic the filepath column in my database.
Here is what a sample filepath column looks like in the column:
jsmith/project1/hello.cs
jsmith/project1/what.cs
jwilliams/project2/hello.cs
I've made a little example. I've test it and it works fine.
Note that I've made a class MyDataBase to simulate your database:
public void CreateTreeView()
{
TreeView myTreeview = new TreeView();
myTreeview.Dock = DockStyle.Fill;
this.Controls.Add(myTreeview);
foreach (string field in MyDataBase.FieldsInMyColumn())
{
string[] elements = field.Split('/');
TreeNode parentNode = null;
for (int i = 0; i < elements.Length - 1; ++i)
{
if (parentNode == null)
{
bool exits = false;
foreach (TreeNode node in myTreeview.Nodes)
{
if (node.Text == elements[i])
{
exits = true;
parentNode = node;
}
}
if (!exits)
{
TreeNode childNode = new TreeNode(elements[i]);
myTreeview.Nodes.Add(childNode);
parentNode = childNode;
}
}
else
{
bool exits = false;
foreach (TreeNode node in parentNode.Nodes)
{
if (node.Text == elements[i])
{
exits = true;
parentNode = node;
}
}
if (!exits)
{
TreeNode childNode = new TreeNode(elements[i]);
parentNode.Nodes.Add(childNode);
parentNode = childNode;
}
}
}
if (parentNode != null)
{
parentNode.Nodes.Add(elements[elements.Length - 1]);
}
}
}
EDIT
Here I paste my auxiliar code, that you don´t need, but it will help you to understand my code, or to copy/paste and try it by yourself.
public static class MyDataBase
{
private static List<string> fields = new List<string>();
public static void AddField(string field)
{
fields.Add(field);
}
public static IList<string> FieldsInMyColumn()
{
return fields;
}
}
Constructor in form1
public Form1()
{
InitializeComponent();
MyDataBase.AddField("jsmith/project1/hello.cs");
MyDataBase.AddField("jsmith/project1/what.cs");
MyDataBase.AddField("jsmith/project2/hello.cs");
CreateTreeView();
}
精彩评论