【问题标题】:Onclick Event on a dynamically created ButtonField in GridView c#在 GridView c# 中动态创建的 ButtonField 上的 Onclick 事件
【发布时间】:2018-03-10 03:29:35
【问题描述】:

我在 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 的工作原理!

任何帮助都会很棒!

【问题讨论】:

  • 你什么时候创建那个按钮?
  • ButtonField 正在范围顶部启动,按钮在页面加载时添加到列中。

标签: c# asp.net gridview event-handling


【解决方案1】:

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

【讨论】:

  • 这和你的@dan6657有什么不同?
  • 我认为这只是 OnRowCommand="GridView1_RowCommand" 和 e.Command 名称 - 谢谢!
  • 真棒@dan6657,我会在答案中强调这一点
  • 另一个快速的如果可以的话,如果在列中的每一行中都设置了这个按钮,并且在不同的列中但在同一行中有一些数据,我是否能够以相同的方式访问相同的行数据行按钮,如果你明白我的意思?我在考虑 foreach/for 循环,但是它们只是遍历集合并根据循环中 x 的任何值将其打印出来。编辑:我可以做类似 rowID 的事情,然后如果按钮 x 在 rowID x 中,给我该行中的数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多