Spread for ASP.NET中提供了级联和分组两种形势显示树形结构的数据,今天将讲解如何扩展Spread实现平铺的树形结构。要使用Spread实现平铺的树形结构,我们需要扩展单元格类型,在单元格类型中完成数据的缩进、节点图片、节点单击事件等操作。
实现我们定义树形结构的节点实体类型,代码如下:
///
/// BOM 实体类型
///
[Serializable]
public class BOM
{
///
/// ID
///
public int ID
{ get; set; }
///
/// 上级ID
///
public int ParentID
{ get; set; }
///
/// 编号
///
public string Code
{ get; set; }
///
/// 层级
///
public int Level
{ get; set; }
// 行号
public int RowNo
{ get; set; }
///
/// 行的折叠/张开状态
///
public int Expand
{ get; set; }
public static List BuildTree(DataTable data)
{
List tree = new List();
foreach (DataRow row in data.Rows)
{
BOM item = new BOM();
item.ID = int.Parse(row["ID"].ToString());
item.ParentID = int.Parse(row["ParentID"].ToString());
item.Code = row["编号"].ToString();
item.Level = int.Parse(row["层级"].ToString());
item.RowNo = int.Parse(row["行号"].ToString());
item.Expand = 1;
tree.Add(item);
}
return tree;
}
}
然后,我们创建自定义的节点单元格类型,代码如下:
///
/// BOM单元格类型
///
[Serializable]
public class BOMCellType : FarPoint.Web.Spread.GeneralCellType
{
///
/// 存放当前数据集中的 BOM 结构
///
public List BOMItems;
public BOMCellType()
{
BOMItems = new List();
}
// 绘制 BOM 单元格的显示外观
public override Control PaintCell(string id, TableCell parent, FarPoint.Web.Spread.Appearance style, FarPoint.Web.Spread.Inset margin, object value, bool upperLevel)
{
BOM item = BOMItems.Where(s => s.ID == int.Parse(value.ToString())).First();
Table table = new Table();
TableRow row = new TableRow();
// 节点缩进
TableCell cell0 = new TableCell();
cell0.Width = 50 * item.Level;
// 节点图标
TableCell cell1 = new TableCell();
string url = GetImage(item);
if (url != "")
{
// 当前节点有子节点,需要设置当前节点的显示图片
cell0.Width = 50 * item.Level - (item.Level == 0 ? 0 : 16);
System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
image.ImageUrl = url;
image.Attributes.Add("onclick", string.Format("NodeClick({0},{1})", item.ID, (item.Expand == 1 ? 0 : 1)));
cell1.Controls.Add(image);
}
// 添加缩进
row.Cells.Add(cell0);
// 添加节点图片
row.Cells.Add(cell1);
// 节点文本
TableCell cell2 = new TableCell();
Label label = new Label();
label.Text = item.Code;
cell2.Controls.Add(label);
row.Cells.Add(cell2);
table.Rows.Add(row);
return table;
}
// 返回节点图片地址
private string GetImage(BOM item)
{
string url = "";
var nodes = BOMItems.Where(s => s.ParentID == item.ID).Count();
if (nodes > 0)
{
if (item.Expand == 1)
url = @"Icon\Expand.gif";
else
url = @"Icon\Collapse.gif";
}
return url;
}
}
运行截图:
源码下载: