萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> 資料庫綜合

ASP.NET GridView 取得 ButtonField/HyperLinkField Text 值的正確姿勢

在 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) **皆回傳空字串**。

正確解法:透過 Controls 集合存取內嵌控制項

1. HyperLinkField — 強制轉型為 HyperLink

// RowDataBound 事件中
if (e.Row.RowType == DataControlRowType.DataRow)
{
    HyperLink hl = (HyperLink)e.Row.Cells[1].Controls[0];
    string linkText = hl.Text;           // 顯示文字
    string navigateUrl = hl.NavigateUrl; // 導向網址
}

2. ButtonField — 強制轉型為 Button (或 LinkButton/ImageButton)

// 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];
}

3. 通用安全寫法:判斷控制項型別

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 取值

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] 取得內嵌控制項
直接轉型不檢查 RowTypeHeader/Footer/DataRow 結構不同,Header 無 Controls[0]先 if (e.Row.RowType == DataControlRowType.DataRow)
ButtonField 設為 LinkButton 仍轉型 Button型別不符拋出 InvalidCastException依 ButtonType 決定轉型目標

RowCommand 事件中取值

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 任何樣板欄位的值都能輕鬆取得。

copyright © 萬盛學電腦網 all rights reserved