How do I display non-normalized data in a hierarchical structure?

前端 未结 3 1137
盖世英雄少女心
盖世英雄少女心 2021-01-16 13:01

My issue is that I want to display data in a hierarchal structure as so:

  • Democrat
    • County Clerk
      • Candidate 1
      • Candidate 2
3条回答
  •  情歌与酒
    2021-01-16 13:36

    If you can modify the stored procedure, I would recommend a result set in the form of an adjacency list:

    ID    Name          ParentID
    1     Democrat      NULL
    2     County Clerk  1
    3     Magistrate    1
    4     Candidate 1   2
    5     Candidate 2   2
    6     Candidate 1   3
    7     Candidate 2   3
    8     Candidate 3   3
    

    It reduces the amount of data retrieved, and allows you to program recursively against the parent-child relationships. You simply start at the root. This approach avoids the hassle of using nested Repeaters by directly building the string literal in a StringBuilder.

    StringBuilder sb = new StringBuilder();
    DataTable dt = new DataTable();
    someDataAdapter.Fill(dt);
    
    // find the roots:
    DataRow[] roots = dt.Select("parentId is null");
    
    sb.Append("
      "); foreach (DataRow child in roots) { WriteNode(child, sb); } sb.Append("
    "); // recursively write out each node public static void WriteNode(DataRow row, StringBuilder sb) { sb.Append("
  • "); sb.Append(row["Name"]); // find children rows... DataRow[] children = row.Table.Select("parentId = " + row["id"].ToString()); if (children.Length > 0) { sb.Append("
      "); foreach (DataRow child in children) { WriteNode(child, sb); } sb.Append("
    "); } sb.Append("
  • "); }

提交回复
热议问题