改 ASP.NET 舊專案的畫面時遇到一個小坑:DataGrid 本身有 CssClass 屬性可以套樣式,但按鈕列(ButtonColumn)卻沒有。也就是說,你沒辦法像一般列那樣在設計階段指定 class,只能從程式碼下手。
為 DataGrid 掛上 ItemCreated 事件,在事件裡取得該列的按鈕控制項,再指定它的 CssClass。
<asp:DataGrid id="dgBoxList" runat="server"
OnItemCreated="dgBoxList_ItemCreated">
...
</asp:DataGrid>
private void dgBoxList_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// 只處理資料列與隔行變色列,跳過表頭、頁尾等
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Button myButton = (Button)e.Item.Cells[2].Controls[0];
myButton.CssClass = "button";
}
}
這段程式最容易出錯的地方就是索引,筆記如下:
Cells[i] 的 i 是欄位索引,從 0 開始。若按鈕在第三欄,i 就是 2。Controls[j] 的 j 是該儲存格內第幾個控制項,一般只有一個控制項,所以 j 為 0。寫死的索引很脆弱:只要日後在 DataGrid 前面插入一個欄位,所有索引都得重算。實務上比較穩妥的做法是用 FindControl 或改用 TemplateColumn 搭配 ItemTemplate,直接在樣板裡寫好 class,就不必靠事件補救了。
把樣式抽到 CSS 而不是寫在 ForeColor、BackColor 這類伺服器端屬性上,有幾個明顯好處:視覺調整不必重新編譯、同一套 class 能在多個 DataGrid 間共用、換主題時只改 CSS 檔即可。這也是「樣式與程式分離」原則在 Web Forms 時代的實踐方式。