我已在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就可以了!
任何帮助都会很棒!
答案 0 :(得分: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);
}
}
}