在应用系统开发过程中,我们经常会有这样的需求,在表格的首列或者最后一列中放置一些操作按钮,比如:删除、修改,查看详细数据等。Spread for ASP.NET本身提供了超链接单元格类型 HyperLinkCellType ,但是在应对以上需求时,我们可以扩展 HyperLinkCellType 单元格类型的行为。
首先,我们定义一个名为 Action 的类型,用于表示每一个操作,代码如下:
///
/// 操作类型
///
[Serializable]
public class Action
{
public Action(string name, string url, string image)
{
this.Name = name;
this.NavigateUrl = url;
this.ImageUrl = image;
}
///
/// 操作名称
///
public string Name
{ get; set; }
///
/// 链接地址
///
public string NavigateUrl
{ get; set; }
///
/// 图片地址
///
public string ImageUrl
{ get; set; }
}
因为需要在自定义的单元格类型中使用,所以,我们给 Action 打上了 Serializable 属性。
接下来我们需要实现自定义的超链接单元格类型 CActionCellType,主要是重写 PaintCell 方法,并根据需要的操作类型返回相应的呈现结果,代码如下:
[Serializable]
public class CActionCellType : FarPoint.Web.Spread.HyperLinkCellType
{
///
/// 制定是需要的操作
///
public List Actions = new List();
// 重写单元格绘制过程
public override Control PaintCell(string id, TableCell parent, FarPoint.Web.Spread.Appearance style, FarPoint.Web.Spread.Inset margin, object value, bool upperLevel)
{
if (value != null)
{
Table table = new Table();
table.GridLines = GridLines.None;
TableRow row = new TableRow();
// 根据指定的操作绘制单元格的内容,并将单元格的Value链接页面的访问参数
foreach (Action item in Actions)
{
TableCell cell = new TableCell();
cell.BorderStyle = BorderStyle.None;
HyperLink link = new HyperLink();
link.ToolTip = item.Name;
link.NavigateUrl = string.Format(item.NavigateUrl, value);
link.ImageUrl = item.ImageUrl;
cell.Controls.Add(link);
row.Cells.Add(cell);
}
table.Rows.Add(row);
return table;
}
else
{
return base.PaintCell(id, parent, style, margin, value, upperLevel);
}
}
}
最后一步就是使用自定义的单元格类型,代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 设置Spread控件的基本属性
FpSpread1.ActiveSheetView.DataAutoCellTypes = false;
FpSpread1.Columns[0].Width = 130;
FpSpread1.Columns[1].Width = 300;
FpSpread1.Columns[2].Width = 100;
FpSpread1.Columns[3].Width = 100;
// 创建一个拥有删除,编辑和查看功能的单元格
CActionCellType action = new CActionCellType();
action.Actions.Add(new Action("删除", "/Page1.aspx?id={0}", "/Images/Delete.png"));
action.Actions.Add(new Action("编辑", "/Page2.aspx?id={0}", "/Images/Edit.png"));
action.Actions.Add(new Action("详细", "/Page3.aspx?id={0}", "/Images/Detail.png"));
FpSpread1.ActiveSheetView.Columns[0].CellType = action;
// 绑定数据源
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("名称");
dt.Columns.Add("分类");
dt.Columns.Add("单价");
dt.Rows.Add(100001, "Spread .NET 表格控件 V6.0", "表格控件", "10000");
dt.Rows.Add(100001, "ActionReports 报表控件 V7.0", "报表控件", "10000");
dt.Rows.Add(100001, "ComponentOne 控件套包 2012V3", "控件套包", "10000");
FpSpread1.DataSource = dt;
}
}
运行截图:
源码下载 VS2010 + Spread .NET 6.0 + C# :
