2017-09-28 114 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

相关问题