GridView裡面使用Button事件

我用了微軟的GridView來達成下圖的畫面,在以前使用的習慣是使用Client端的事件再配合javascript來完成資料更新,因此沒有嘗試過Server的事件,這次我直接在ItemTemplate中直接放入一個Button(下圖藍框處)並在RowDateBound中動態加上事件如下,
Button btn = new Button();

btn = (Button)e.Row.FindControl("Button1");
btn.Text = e.Row.RowIndex.ToString();
btn.ID = e.Row.RowIndex.ToString();
btn.Click += new EventHandler(btn_Click);


但是在OnClick事件當中卻永遠都抓不到值(正確來說是完全沒有執行到,除非在RowDataBound中直接使用Click事件才會執行),最後使用了ButtonField物件(下圖紅框處),並在RowCommand當中取到了正確的值解決了這個問題。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Button btn = new Button();
        TextBox txt = new TextBox();
        //btn = ((Button)e.Row.Cells[2].Controls[1]);
        //btn = (Button)e.Row.FindControl("Button1");
        txt = (TextBox)e.Row.FindControl("TextBox_amount");
        txt.Style["text-align"] = "right";
        txt.Style["width"] = "110px";
        ((Button)e.Row.Cells[3].Controls[0]).Attributes.Add("onclick", "if(!window.confirm('確定要刪除嗎?')) return;");
    }
}
//GridView按鈕事件
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    string strKey = "", strAmount = "";
    TextBox txt = new TextBox();
    txt = (TextBox)GridView1.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("TextBox_amount");
    strAmount = txt.Text;
    strKey = new Guid(GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)]["ordetailid"].ToString()).ToString();
    if (e.CommandName.CompareTo("btn_Save") == 0)
    {
        //Do Smonthing
    }
}

留言