ASP.NET 2.0 GridView 設定 Visible="false" 隱藏欄位後,後置程式碼無法取得該欄位值 —— 這與 DataGrid 行為不同,是遷移專案常見的坑。本文提供三種解決方案,從簡潔到進階逐一分析。
protected void GVList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow ||
e.Row.RowType == DataControlRowType.Header ||
e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Visible = false; // 隱藏第 1 欄
e.Row.Cells[3].Visible = false; // 隱藏第 4 欄
}
}
在資料繫結階段隱藏 Cell,資料已繫結完成,後置程式碼仍可透過 row.Cells[index].Text 取值。
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow ||
e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
// 可依需求隱藏更多欄位
}
}
RowCreated 發生於資料繫結之前,此時隱藏不影響資料繫結過程,同樣可在後續事件中存取隱藏欄位值。
public void MyTestFunction()
{
string conString = "...";
string sqlQuery = "...";
SqlConnection con = new SqlConnection(conString);
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds);
// 關鍵:將第 0 欄對應類型設為 Hidden
ds.Tables[0].Columns[0].ColumnMapping = MappingType.Hidden;
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
此法在資料來源層面標記欄位不輸出,GridView 自動不渲染該欄,但資料仍保留於 DataTable 中供程式存取。
| 方案 | 優點 | 適用場景 |
|---|---|---|
| RowDataBound | 程式碼最少、直觀 | 簡單隱藏需求、快速修正既有專案 |
| RowCreated | 生命週期更早、效能略優 | 大量資料、複雜樣板欄位 |
| ColumnMapping | 關注點分離、不污染 UI 邏輯 | 架構導向專案、資料層獨立設計 |
核心原理皆為:資料繫結完成後再隱藏呈現,而非繫結前移除資料。