dataview做无限极分类的又一用法

通常看到别人以及自己以前在绑定无限极分类的时候,总是需要多次连接数据库,这样觉得造成了资源的浪费,然后我想一次把所有数据先取出来(类型不是很多的情况),这样可以节省服务器的开销,数据库结构:

classidid                     主键
jobClassName          对应的类型名称
ClassName        对应的父类的id

通常做法:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
private void Display(string parentid, String space)
ExpandedBlockStart.gifContractedBlock.gif     
{
         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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
           
foreach (DataRow dr in dt.Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                strOpinion 
+= space + "<font color=red>[" + dr["JobClassName"].ToString() +"<br>";
                Display(dr[
"ClassID"].ToString(), "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + space,false);
            }

        }

    }

很明显,这种做法是每个父分类都得建立一次连接,完全浪费资源

现在一次取出所有分类,使用DataView的RowFilter属性做多次过滤

关键代码

 

ContractedBlock.gif ExpandedBlockStart.gif Code
public partial class tree_Default : System.Web.UI.Page
ExpandedBlockStart.gifContractedBlock.gif
{
    DataTable dt 
= null;
    
protected void Page_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
if (!IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            bind(
0);
        }

    }


    
public void bind(int pid)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        DataTable dt1 
= bindTree(pid);
        
foreach (DataRow dr in dt1.Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
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)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
if (dt == null)
            dt 
= new data().getCatelogs();
        DataView root 
= dt.DefaultView;
        root.RowFilter 
= "Parentid=" + pid;
        
return root.ToTable();
    }

}

这样的话,也就没必要浪费资源的了。

其实这篇文章有些牵强了,一般分类都很少做改动的,直接用缓存或静态化处理就可以了,只是想到了记录一下O(∩_∩)O~。


 

转载于:https://www.cnblogs.com/IT-Cristian/archive/2009/11/01/1594027.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值