PC 採購流程系統需「從核准申請單勾選生成訂單」,介面需支援:核取方塊選取、自動計算總價、分組顯示。選用 SharePoint 內建 SPGridView 實作。
SPGridView 無內建 CheckBox 欄,需實作 ITemplate:
class CheckBoxTemplateField : ITemplate
{
string _id; EventHandler _onCheck;
public CheckBoxTemplateField(string id, EventHandler onCheck)
{ _id = id; _onCheck = onCheck; }
public void InstantiateIn(Control container)
{
var chb = new CheckBox { AutoPostBack = true, ID = _id };
chb.CheckedChanged += _onCheck;
container.Controls.Add(chb);
}
}
protected override void CreateChildControls()
{
SPList sourceList = SPContext.Current.Web.Lists["Purchase Request"];
var dataSource = new SPDataSource { List = sourceList };
this.Controls.Add(dataSource);
var gridView = new SPGridView { AutoGenerateColumns = false };
// CheckBox 模板欄
var chbField = new TemplateField { HeaderText = "" };
chbField.ItemTemplate = new CheckBoxTemplateField("chb", new EventHandler(OnCheck));
gridView.Columns.Add(chbField);
// 一般欄位輔助方法
gridView.Columns.Add(CreateBoundField("Created", "Created"));
gridView.Columns.Add(CreateBoundField("Created By", "Created By"));
gridView.Columns.Add(CreateBoundField("Machine Type", "Machine Type"));
// ... 其餘欄位
// 啟用群組:依 Team 分組
gridView.AllowGrouping = true;
gridView.AllowGroupCollapse = true;
gridView.GroupField = "Team";
gridView.GroupFieldDisplayName = "Team";
// DataKeyNames 保存關鍵資料
gridView.DataKeyNames = new[] { "ID", "Team", "Total Price", /*...*/ };
this.Controls.Add(gridView);
}
Team 為 Lookup 型別,直接群組會顯示 23;#SharePoint Test(ID;#Value)。需在 RowDataBound 修正:
void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (sender as SPGridView).AllowGrouping)
{
var gridRow = e.Row as SPGridViewRow;
if (gridRow != null && gridRow.HeaderText != null)
{
var raw = DataBinder.GetPropertyValue(e.Row.DataItem, ((SPGridView)sender).GroupField).ToString();
gridRow.HeaderText = "Team : " + new SPFieldLookupValue(raw).LookupValue;
}
}
}
string machineType = gridView.DataKeys[row.RowIndex].Values["Machine Type"].ToString();
WebPart 中存取 SharePoint Session 拋異常,web.config 已啟用 Session Module 與 <pages enableSessionState="true">,原因未查明,改用 Context.Cache 替代。歡迎高手指教。
SPGridView 用法不複雜,關鍵在釐清業務邏輯、善用模板欄位、處理 Lookup 群組顯示、活用 DataKeyNames 傳遞隱藏資料。