GridView 綁定數據源,需根據當前行實體的 IsSendGoods 屬性動態顯示/隱藏某列(如「發貨」按鈕列)。
在後台寫獨立方法遍歷 GridView.Rows 設置 Visible,時機錯誤(數據未綁定)、且無法針對單行單列控制。
<asp:GridView ID="gvOrders" runat="server" OnRowDataBound="gvOrders_RowDataBound" ... >
<Columns>
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:LinkButton ID="btnShip" runat="server" Text="發貨" Visible='<%# !Eval("IsSendGoods") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gvOrders_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
// 方式一:綁定表達式已處理(見上方 Visible='<%# ... %>'),此處可做複雜邏輯
var order = (OrderModel)e.Row.DataItem;
// 方式二:代碼控制(如需動態查找控件)
LinkButton btnShip = (LinkButton)e.Row.FindControl("btnShip");
if (btnShip != null) {
btnShip.Visible = !order.IsSendGoods;
}
// 方式三:直接操作 Cell(不推薦,列索引易變)
// e.Row.Cells[9].Visible = !order.IsSendGoods;
}
}
RowDataBound 在每行數據綁定**完成後**觸發,e.Row.DataItem 即當前行實體對象。Visible='<%# !Eval("IsSendGoods") %>' 聲明式綁定,代碼量最少、可維護性最好。e.Row.FindControl("ControlID") 獲取模板內控件實例,再設置屬性。e.Row.Cells[9] 列調序即失效,改用控件 ID 或綁定表達式。GridView 動態控制列顯示,**掛載 RowDataBound 事件**,在其中通過 e.Row.DataItem 獲取實體,**優先用模板列綁定表達式**,複雜邏輯用 FindControl 操作具體控件。別在外部方法遍歷 Rows,時機與上下文都不對。