我在GridView中动态创建了一个列,以在每行中出现一个按钮。并试图让一个on iclick活动上班。
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 Works!
任何帮助都很好!
您需要实现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);
}
}
}