首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

GridViewRow 任意位置點擊觸發事件的實作技巧

     編輯:關於ASP.NET

需求場景

ASP.NET 2.0 中 GridView 是最常用的資料呈現控制項。若需求為「點擊資料列任意位置即觸發超連結或進入編輯模式」,預設行為無法滿足,需自行注入客戶端屬性。

實作步驟

  1. 資料繫結:
private void BindData()
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
}
  1. 在 RowDataBound 事件為每列加入 onclick 屬性:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string script = "alert('Row index: " + e.Row.RowIndex + "');";
        e.Row.Attributes.Add("onclick", script);
        // 實際應用可換為:window.location.href = 'Detail.aspx?id=' + DataKey.Value;
    }
}

進階應用

  • 搭配 DataKeys 取得主鍵值,導向詳細頁或觸發 __doPostBack 進入編輯模式。
  • 可加入滑鼠游標樣式 e.Row.Style["cursor"] = "pointer" 提升可發現性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved