根据指定ID,返回包含该ID的所有父级记录

///************************************************************************
/// Descript:
/// 根据指定分类ID,返回包含该ID在内的所有父级分类ID
/// Author:Blue.Dream
/// CreateDate:2004年9月6日, 8:55:32
/// ModifyDate:2004年10月6日, 16:12:28
///
///************************************************************************

///

1<summary>   
2/// 根据ID的所有父级分类   
3/// </summary>

public class ExecuteClass
{
private DataTable SourceTable; //要分类的表
private DataTable ParentTable; //存放父级分类的表
private DataTable ObjectTable; //存放结果表
private int ID; //要处理的ID
private string ParentID; //父级分类字段名称
private string PriID; //主键标识ID

//初始化
public ExecuteClass(DataTable st,int id,string parentid,string priid)
{
SourceTable = new DataTable();
SourceTable = st.Copy();
ID = id;
ParentID = parentid;
PriID = priid;
ParentTable = new DataTable("Parent");
ParentTable = st.Clone();
ObjectTable = new DataTable("Object");
ObjectTable = st.Clone();
Execute();
}

public DataTable GetResult
{
get
{
return this.ObjectTable;
}
}

private void Execute()
{
InsertParent(ID);
ExecuteParent(ID);
int len = ParentTable.Rows.Count - 1;
for(int i = len; i >= 0; i--)
{
DataRow row = ObjectTable.NewRow();
for(int j = 0; j < ParentTable.Columns.Count; j++)
{
row[j] = ParentTable.Rows[i][j];
}
ObjectTable.Rows.Add(row);
}
}
//处理所有父级ID
private void ExecuteParent(int id)
{
DataView dv = SourceTable.DefaultView;
dv.RowFilter = PriID + " = " + id.ToString();
if(dv.Count > 0) //如果有此记录,则查看此记录的父级ID是否为0,如果不为0,则递归
{
int parID = Int32.Parse(dv[0][ParentID].ToString());
if(parID > 0) //如果有父级ID
{
//将此条信息加入父级分类临时表
InsertParent(parID);
//递归调用
ExecuteParent(parID);
}
}
}

//添加到父级临时表
//此处可以使用DataTalbe.Select()方法
private void InsertParent(int i)
{
foreach(DataRow row in SourceTable.Rows)
{
if(Int32.Parse(row[PriID].ToString()) == i)
{
DataRow r = ParentTable.NewRow();
for(int j = 0; j < SourceTable.Columns.Count; j++)
{
r[j] = row[j];
}
ParentTable.Rows.Add(r);
break;
}
}
}

}
说明:根据这个还可以返回树型表的所有一级分类及子分类列表,至于如何实现,我就不写了.

Published At
Categories with Web编程
Tagged with
comments powered by Disqus