[程式] 動態新增按鈕,並且綁定 Command 事件(及非動態置入按鈕)
我的例子是寫在 GridView 的 RowDataBound 中。
使用 Command 而不用一般的 click 事件,是因為 Command 可以順便帶入一些參數,方便程式判斷。
如果不需要帶入參數的事件,用 click 事件即可。
protected void GV1_RowDataBound(object sender, GridViewRowEventArgs e) { LinkButton vLBTN = new LinkButton(); vLBTN.ID = "LBTNstatusShow" + e.Row.RowIndex; vLBTN.Text = "顯示"; vLBTN.CommandName = "Show"; vLBTN.CommandArgument = GV1.DataKeys[e.Row.RowIndex].Values[0].ToString(); vLBTN.Command += new CommandEventHandler(CommandStatusBtn_Click); //如果只是一般的 click 事件則是:vLBTN.Click += new EventHandler(CommandStatusBtn_Click); e.Row.Cells[5].Controls.Add(vLBTN); } protected void CommandStatusBtn_Click(object sender, CommandEventArgs e) { string vArgu = e.CommandArgument.ToString(), vName = e.CommandName; //略 }
PS1: 如果按鈕是動態產生的,觸發事件時,按鈕要比事件發生前還要先生成出來到畫面上,事件才有作用。
PS2: 或是直接 GridView 的欄位中放入按紐
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" ....(略) <asp:TemplateField> <ItemTemplate> <asp:Button ID="btnEdit" runat="server" CausesValidation="False" CommandName="Edit_Command" Text="編輯" Font-Bold="True" CommandArgument='<%# Eval("ID") %>' ForeColor="Red" /> </ItemTemplate> </asp:TemplateField>並於 cs 檔案中寫觸發 method
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { }