ASP.NET 2.0 中 GridView 是最常用的資料呈現控制項。若需求為「點擊資料列任意位置即觸發超連結或進入編輯模式」,預設行為無法滿足,需自行注入客戶端屬性。
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();
}
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" 提升可發現性。