在 GridView 中,BoundField 可直接用 e.Row.Cells[i].Text 取值,但 ButtonField、HyperLinkField、TemplateField 等控制項欄位,**文字屬於內嵌控制項**,需透過 Controls 集合存取。本文示範正確取值方式。
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Name" HeaderText="姓名" />
<asp:HyperLinkField DataTextField="LinkText" HeaderText="連結" />
<asp:ButtonField ButtonType="Button" Text="編輯" HeaderText="操作" />
</Columns>
</asp:GridView>
嘗試 e.Row.Cells[1].Text (HyperLinkField) 或 e.Row.Cells[2].Text (ButtonField) **皆回傳空字串**。
// RowDataBound 事件中
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hl = (HyperLink)e.Row.Cells[1].Controls[0];
string linkText = hl.Text; // 顯示文字
string navigateUrl = hl.NavigateUrl; // 導向網址
}
// RowDataBound 或 RowCommand 事件中
if (e.Row.RowType == DataControlRowType.DataRow)
{
// ButtonField 預設產生 Button 控制項
Button btn = (Button)e.Row.Cells[2].Controls[0];
string btnText = btn.Text; // "編輯"
// 若 ButtonType="LinkButton",則轉型為 LinkButton
// LinkButton lb = (LinkButton)e.Row.Cells[2].Controls[0];
}
Control ctrl = e.Row.Cells[colIndex].Controls[0];
if (ctrl is HyperLink) { var hl = (HyperLink)ctrl; /* ... */ }
else if (ctrl is Button) { var btn = (Button)ctrl; /* ... */ }
else if (ctrl is LinkButton) { var lb = (LinkButton)ctrl; /* ... */ }
TemplateField 完全由開發者定義控制項,使用 FindControl 最穩健:
Label lbl = (Label)e.Row.FindControl("lblName");
TextBox txt = (TextBox)e.Row.FindControl("txtAge");
| 錯誤寫法 | 原因 | 正確做法 |
|---|---|---|
e.Row.Cells[i].Text | 控制項欄位不直接輸出 Text 到 Cell | 用 Controls[0] 取得內嵌控制項 |
| 直接轉型不檢查 RowType | Header/Footer/DataRow 結構不同,Header 無 Controls[0] | 先 if (e.Row.RowType == DataControlRowType.DataRow) |
| ButtonField 設為 LinkButton 仍轉型 Button | 型別不符拋出 InvalidCastException | 依 ButtonType 決定轉型目標 |
protected void gvData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditItem")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvData.Rows[rowIndex];
Button btn = (Button)row.Cells[2].Controls[0];
string txt = btn.Text; // 取得按鈕文字
}
}
掌握 Controls 集合與 FindControl 兩大核心技巧,GridView 任何樣板欄位的值都能輕鬆取得。