今天遇到一个问题,就是要把一个有层级关系的数据表的数据用层级的方式展示出来(不是用TreeView),而是在下拉框中展示出来,真的很BT的需求,但是还是要实现的是不,不说废话了,下面就是具体做法
//1.在现有的数据中加一个表示这条数据深度(第几层)的列
在这里,dt是已经充满数据的一个DataTable
//克隆一个表,加上Depth(深度列)
DataTable clondt = dt.Copy();
clondt.Columns.Add("Depth");
MakeTree(dt, clondt);//填充一条数据的深度值
DataTable newdt = clondt.Clone();
SetNewTable(newdt, clondt);//真正的填充层级数据
//2.取得这个深度值,代码如下:
/// <summary>
/// 填充节点层级
/// </summary>
/// <param name="dt"></param>
/// <param name="clondt"></param>
private static void MakeTree(DataTable dt, DataTable clondt)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
int depth = 1;
if (dt.Rows[i]["PARENTCOMPANYID"] != DBNull.Value)
{
depth++;
int parentcompanyId = Convert.ToInt32(dt.Rows[i]["PARENTCOMPANYID"]);
while (HaveLoopParent(dt, ref parentcompanyId))
{
depth++;
}
}
clondt.Rows[i]["Depth"] = depth;
}
}
private static bool HaveLoopParent(DataTable dt, ref int parentcompanyId)
{
DataRow[] drs = dt.Select("COMPANYID=" + parentcompanyId);
if (drs.Length > 0)
{
if (drs[0]["PARENTCOMPANYID"] == DBNull.Value)
return false;
else
{
parentcompanyId = Convert.ToInt32(drs[0]["PARENTCOMPANYID"]);
return true;
}
}
else
return false;
}
//3.填充层级数据
/// <summary>
/// 把层级关系赋值给新的表
/// </summary>
/// <param name="newdt"></param>
/// <param name="clondt"></param>
private static void SetNewTable(DataTable newdt, DataTable clondt)
{
DataRow rootRow = clondt.Select("PARENTCOMPANYID IS NULL")[0];
SetNewRow(newdt, rootRow);
GetChild(rootRow, clondt, newdt);
}
private static void SetNewRow(DataTable newdt, DataRow rootRow)
{
DataRow row = newdt.NewRow();
if (rootRow["Depth"] != DBNull.Value)
{
string line = "";
for (int i = 0; i < Convert.ToInt32(rootRow["Depth"]); i++)
{
line += "| ";
}
row["COMPANYNAME"] = line + "-" + rootRow["COMPANYNAME"];
}
row["COMPANYID"] = rootRow["COMPANYID"];
row["COMPANYNO"] = rootRow["COMPANYNO"];
row["COMPANYCODE"] = rootRow["COMPANYCODE"];
row["RECORDSTATUS"] = rootRow["RECORDSTATUS"];
row["MODIFYUSERID"] = rootRow["MODIFYUSERID"];
row["MODIFYDATE"] = rootRow["MODIFYDATE"];
row["PARENTCOMPANYNO"] = rootRow["PARENTCOMPANYNO"];
row["CreateDate"] = rootRow["CreateDate"];
row["ModifiedOn"] = rootRow["ModifiedOn"];
row["PARENTCOMPANYID"] = rootRow["PARENTCOMPANYID"];
row["Depth"] = rootRow["Depth"];
newdt.Rows.Add(row);
}
private static void GetChild(DataRow rootRow, DataTable clondt, DataTable newdt)
{
DataRow[] childrows = clondt.Select("PARENTCOMPANYID=" + rootRow["COMPANYID"]);
for (int i = 0; i < childrows.Length; i++)
{
DataRow childrow = childrows[i];
SetNewRow(newdt, childrow);
if (clondt.Select("PARENTCOMPANYID=" + childrow["COMPANYID"]).Length > 0)
{
GetChild(childrow, clondt, newdt);
}
}
}