如果可以修改存储过程,则建议以邻接表的形式显示结果集:
ID Name ParentID1 Democrat NULL2 County Clerk 13 Magistrate 14 Candidate 1 25 Candidate 2 26 Candidate 1 37 Candidate 2 38 Candidate 3 3
它减少了检索到的数据量,并允许您针对父子关系进行递归编程。您只需从根开始。通过直接在StringBuilder中构建字符串文字,此方法避免了使用嵌套重复器的麻烦。
StringBuilder sb = new StringBuilder();DataTable dt = new DataTable();someDataAdapter.Fill(dt);// find the roots:DataRow[] roots = dt.Select("parentId is null");sb.Append("<ul>");foreach (DataRow child in roots){ WriteNode(child, sb);}sb.Append("</ul>");// recursively write out each nodepublic static void WriteNode(DataRow row, StringBuilder sb) { sb.Append("<li>"); sb.Append(row["Name"]); // find children rows... DataRow[] children = row.Table.Select("parentId = " + row["id"].ToString()); if (children.Length > 0) { sb.Append("<ul>"); foreach (DataRow child in children) { WriteNode(child, sb); } sb.Append("</ul>"); } sb.Append("</li>"); }


