2017-09-28 115 views
0

我已經動態地在gridview中爲每個按鈕出現在一行中創建一列。我試圖讓一個onclick事件工作。在GridView中動態創建的ButtonField上的Onclick事件c#

ButtonField test = new ButtonField();  
test.Text = "Details"; 
test.ButtonType = ButtonType.Button; 
test.CommandName = "test"; 
GridView1.Columns.Add(test); 

我的ASP基本應有盡有動態添加到GridView:

<asp:GridView ID="GridView1" runat="server"> </asp:GridView> 

這追加的按鈕(一個或多個),但是我似乎罰款不能找到一個參數,添加上點擊事件在測試按鈕字段上。

我已經試過:

void viewDetails_Command(Object sender, GridViewRowEventArgs e) 
    { 
     if (test.CommandName == "test") 
     { 
      ScriptManager.RegisterClientScriptBlock(this, this.GetType(),  "alertMessage", "alert('Event works')", true); 
     } 
    } 

,因爲我認爲它不會綁定到任何東西,但是我看不到,我就這個事件函數綁定到這不跑?只需使用警報消息來測試onclick的作品!

任何幫助將是偉大的!

+0

當您創建按鈕? – hardkoded

+0

ButtonField正在範圍的頂部啓動,按鈕被添加到頁面加載的列中。 – dan6657

回答

0

您需要實施RowCommand事件。

標記:

<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand"> 
</asp:GridView> 

代碼旁邊:

public partial class DynamicGridView : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      var test = new ButtonField(); 
      test.Text = "Details"; 
      test.ButtonType = ButtonType.Button; 
      test.CommandName = "test"; 
      GridView1.Columns.Add(test); 


      GridView1.DataSource = new[] { 
       new {Id= 1, Text = "Text 1" }, 
       new {Id= 2, Text = "Text 2" }, 
      }; 
      GridView1.DataBind(); 
     } 
    } 

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     if (e.CommandName == "test") 
     { 
      ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", "alert('Event works')", true); 
     } 
    } 
} 
+0

這與你的dan6657有什麼不同? – hardkoded

+0

這只是OnRowCommand =「GridView1_RowCommand」和e.Command的名字,我認爲 - 謝謝! – dan6657

+0

真棒@ dan6657,我會在答案中強調 – hardkoded

相關問題