asp.net dataview做无限极分类的又一用法 |
数据库结构: classidid 主键 jobClassName 对应的类型名称 ClassName 对应的父类的id 通常做法: 复制代码 代码如下: private void Display(string parentid, String space) { DataTable dt; String strSQL; strSQL = "Select * From Tree Where ParentID =" + parentid + " Order By ClassID DESC"; SqlDataAdapter sda = new SqlDataAdapter(strSQL, conn); DataSet ds = new DataSet(); sda.Fill(ds, "Tree"); dt = ds.Tables["Tree"]; if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { strOpinion += space + "<font color=red>[" + dr["JobClassName"].ToString() +"<br>"; Display(dr["ClassID"].ToString(), " " + space,false); } } } 很明显,这种做法是每个父分类都得建立一次连接,完全浪费资源 现在一次取出所有分类,使用DataView的RowFilter属性做多次过滤 关键代码 复制代码 代码如下: public partial class tree_Default : System.Web.UI.Page { DataTable dt = null; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bind(0); } } public void bind(int pid) { DataTable dt1 = bindTree(pid); foreach (DataRow dr in dt1.Rows) { int id = Convert.ToInt32(dr["classid"].ToString()); if (pid == 0) Response.Write("<div style=width:100%;float:right;><h3>" + dr["jobclassname"].ToString() + "</h3></div>"); else Response.Write("<div style=width:25%;float:left;>"+dr["jobclassname"].ToString()+"</div>"); bind(id); } } public DataTable bindTree(int pid) { if (dt == null) dt = new data().getCatelogs(); DataView root = dt.DefaultView; root.RowFilter = "Parentid=" + pid; return root.ToTable(); } } 这样的话,也就没必要浪费资源的了 。 其实这篇文章有些牵强了,一般分类都很少做改动的,直接用缓存或静态化处理就可以了,只是想到了记录一下O(∩_∩)O' 。 |