繁体   English   中英

在GridView中动态创建的ButtonField上的Onclick事件c#

[英]Onclick Event on a dynamically created ButtonField in GridView c#

我已经在gridview中动态创建了一个列,以使按钮出现在每一行中。 并试图使onclick事件起作用。

 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即可!

任何帮助将是巨大的!

您需要实现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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM