private void Form19_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("data");
dt.Columns.Add("id",typeof(int));
dt.Columns.Add("ParentId",typeof(int));
dt.Columns.Add("description");
dt.Columns.Add("link");
dt.Rows.Add(1, null, "Root", "www.microsoft.com");
dt.Rows.Add(2, 1, "Child1", "www.microsoft.com");
dt.Rows.Add(3, 1, "Child2", "www.microsoft.com");
dt.Rows.Add(4, 2, "GrandChild1", "www.microsoft.com");
dt.Rows.Add(5, 2, "GrandChild2", "www.microsoft.com");
dt.Rows.Add(6, 2, "GrandChild3", "www.microsoft.com");
dt.Rows.Add(7, 3, "GrandChild4", "www.microsoft.com");
dt.Rows.Add(8, 3, "GrandChild5", "www.microsoft.com");
//Use a DataSet to manage the data
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//add a relationship
ds.Relations.Add("rsParentChild",
{
DataTable dt = new DataTable("data");
dt.Columns.Add("id",typeof(int));
dt.Columns.Add("ParentId",typeof(int));
dt.Columns.Add("description");
dt.Columns.Add("link");
dt.Rows.Add(1, null, "Root", "www.microsoft.com");
dt.Rows.Add(2, 1, "Child1", "www.microsoft.com");
dt.Rows.Add(3, 1, "Child2", "www.microsoft.com");
dt.Rows.Add(4, 2, "GrandChild1", "www.microsoft.com");
dt.Rows.Add(5, 2, "GrandChild2", "www.microsoft.com");
dt.Rows.Add(6, 2, "GrandChild3", "www.microsoft.com");
dt.Rows.Add(7, 3, "GrandChild4", "www.microsoft.com");
dt.Rows.Add(8, 3, "GrandChild5", "www.microsoft.com");
//Use a DataSet to manage the data
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//add a relationship
ds.Relations.Add("rsParentChild",
ds.Tables["data"].Columns["id"],
ds.Tables["data"].Columns["ParentId"]);
foreach (DataRow dr in ds.Tables["data"].Rows)
{
if (dr["ParentId"] == DBNull.Value)
foreach (DataRow dr in ds.Tables["data"].Rows)
{
if (dr["ParentId"] == DBNull.Value)
{
TreeNode root = new TreeNode(dr["description"].ToString());
root.Tag = dr["link"].ToString();
treeView1.Nodes.Add(root);
PopulateTree(dr, root);
}
}
TreeNode root = new TreeNode(dr["description"].ToString());
root.Tag = dr["link"].ToString();
treeView1.Nodes.Add(root);
PopulateTree(dr, root);
}
}
treeView1.ExpandAll();
}
public void PopulateTree(DataRow dr, TreeNode pNode)
{
foreach (DataRow row in dr.GetChildRows("rsParentChild"))
{
TreeNode cChild = new TreeNode(row["description"].ToString());
cChild.Tag = row["link"].ToString();
}
public void PopulateTree(DataRow dr, TreeNode pNode)
{
foreach (DataRow row in dr.GetChildRows("rsParentChild"))
{
TreeNode cChild = new TreeNode(row["description"].ToString());
cChild.Tag = row["link"].ToString();
pNode.Nodes.Add(cChild);
//Recursively build the tree
PopulateTree(row, cChild);
}}
Populate TreeView node with datatable in C#.NET
ОтветитьУдалить