C# 获取SQL数据库节点信息并绑定到TreeView - 图1
    代码:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Data;
    4. using System.Data.SqlClient;
    5. using System.Linq;
    6. using System.Text;
    7. using System.Windows.Forms;
    8. namespace Sign_plate_management_system
    9. {
    10. public static class BindTVData
    11. {
    12. private static DataTable dt = null;
    13. //获取数据库所有数据
    14. public static DataTable InitDataTable()
    15. {
    16. SqlConnection conn = new SqlConnection($"Server={ MyDBControls.Server };database={ MyDBControls.Dbase};uid={ MyDBControls.Uid };pwd={ MyDBControls.Pwd}");
    17. SqlDataAdapter sda = new SqlDataAdapter("select * from TVNodesInfo", conn);
    18. dt = new DataTable();
    19. sda.Fill(dt);
    20. return dt;
    21. }
    22. //绑定根节点
    23. public static void BindRootNode(TreeView trv)
    24. {
    25. DataRow[] rows = InitDataTable().Select("NodeTagID=0");
    26. //取根
    27. foreach (DataRow dRow in rows)
    28. {
    29. TreeNode rootNode = new TreeNode
    30. {
    31. Tag = (int)dRow["ID"],
    32. Text = dRow["NodeText"].ToString(),
    33. Name= dRow["NodeName"].ToString()
    34. };
    35. trv.Nodes.Add(rootNode);
    36. BindChildNode(rootNode);
    37. }
    38. }
    39. //递归绑定子区域
    40. private static void BindChildNode(TreeNode FNode)
    41. {
    42. //父节点数据关联的数据行
    43. int nodetagId = (int)FNode.Tag;
    44. //父节点ID
    45. DataRow[] rows = dt.Select($"NodeTagID={nodetagId}");
    46. //子区域
    47. if (rows.Length == 0)//递归终止,区域不包含子区域时
    48. {
    49. return;
    50. }
    51. foreach (DataRow dRow in rows)
    52. {
    53. TreeNode node = new TreeNode
    54. {
    55. Tag = (int)dRow["ID"],
    56. Text = dRow["NodeText"].ToString(),
    57. Name = dRow["NodeName"].ToString()
    58. };
    59. //添加子节点
    60. FNode.Nodes.Add(node);
    61. //递归
    62. BindChildNode(node);
    63. }
    64. }
    65. }
    66. }