在 RowDataBound 事件中為刪除連結按鈕動態加入 JavaScript 確認對話框,並傳遞資料鍵值:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton btnDelete = (LinkButton)e.Row.FindControl("LinkButton1");
string id = DataBinder.Eval(e.Row.DataItem, "編號").ToString();
btnDelete.Attributes.Add("onclick",
"return confirm('確定要刪除編號 " + id + " 的記錄嗎?');");
}
}
DataBinder.Eval 取得當前資料列的主鍵值。return confirm(...) 若使用者點取「取消」會回傳 false,中止 Postback。CommandName="Delete" 的 LinkButton 或 Button。