C# 从代码隐藏添加 OnClick 到按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19053694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:59:28  来源:igfitidea点击:

Add OnClick to button from codebehind

c#asp.netbuttononclick

提问by techora

I am trying to add an OnClick attribute to a button from the code behind. Depending if the Attending element is 0 or not will determine which OnClick attribute gets added. When I click the button with the code below I get the following error:

我正在尝试从后面的代码中向按钮添加 OnClick 属性。根据出席元素是否为 0 将确定添加哪个 OnClick 属性。当我单击带有以下代码的按钮时,出现以下错误:

"Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."

“Microsoft JScript 运行时错误:Sys.WebForms.PageRequestManagerServerErrorException:无效的回发或回调参数。在页面中使用配置或 <%@ Page EnableEventValidation="true" %> 启用事件验证。出于安全目的,此功能验证该参数回发或回调事件源自最初呈现它们的服务器控件。如果数据有效且符合预期,请使用 ClientScriptManager.RegisterForEventValidation 方法注册回发或回调数据以进行验证。”

What am I doing wrong?

我究竟做错了什么?

ASPX

ASPX

<%@ Page Title="" Language="C#" EnableEventValidation="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="test.CommunityEvents.Default" %>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:DataList ID="DataList1" RepeatColumns="1" CellPadding="5" OnItemDataBound="Dl1_ItemDataBound"
            runat="server">
            <ItemTemplate>
                   <div id="Attendingbox" runat="server">
                       <asp:Label ID="AttendingorNot" runat="server"></asp:Label>
                    </div>
                    <br />
                    <asp:Button ID="SignupButton" runat="server" Text="" />
            </ItemTemplate>
        </asp:DataList>
    </ContentTemplate>
</asp:UpdatePanel>

Code Behind

背后的代码

protected void Dl1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            .....//removed other code to save space

            Button SignupButton = (Button)e.Item.FindControl("SignupButton");
            if (Attending == 0)
            {
                AttendingorNot.Text = "You are not attending";
                AttendingorNot.Attributes.Add("class", "alert");
                SignupButton.Text = "Attend";
                SignupButton.Attributes.Add("class", "btn btn-large btn-success");
                SignupButton.Click += new EventHandler(Submit_Add);
            }
            else
            {
                AttendingorNot.Text = "You are attending!";
                AttendingorNot.Attributes.Add("class", "alert alert-success");
                SignupButton.Text = "Remove";
                SignupButton.Attributes.Add("class", "btn btn-large btn-danger");
                SignupButton.Click += new EventHandler(Submit_Remove);
            }
        }
    }
    private void Submit_Remove(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?msg=work");
    }
    private void Submit_Add(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?msg=gone");
    }

回答by Win

If you want to attach button's event dynamically, you want to use button's CommandName, and catch the event in ItemCommand event.

如果要动态附加按钮的事件,则需要使用按钮的 CommandName,并在 ItemCommand 事件中捕获该事件。

The main advantage is that you can capture which row is clicked.

主要优点是您可以捕获单击了哪一行。

protected void Dl1_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || 
       e.Item.ItemType == ListItemType.AlternatingItem)
    {
        .... 
        Button SignupButton = (Button)e.Item.FindControl("SignupButton");
        if (Attending == 0)
        {
            SignupButton.Text = "Attend";
            SignupButton.Attributes.Add("class", "btn btn-large btn-success");
            SignupButton.CommandName = "Attend";
        }
        else
        {
            SignupButton.Text = "Remove";
            SignupButton.Attributes.Add("class", "btn btn-large btn-danger");
            SignupButton.CommandName = "Remove";
        }
    }
}

protected void Dl1_ItemCommand(object source, DataListCommandEventArgs e)
{
    if (e.CommandName == "Attend")
    {
        Response.Redirect("Default.aspx?msg=work");
    }
    else if (e.CommandName == "Remove")
    {
        Response.Redirect("Default.aspx?msg=gone");
    }
}

回答by deru

Use this

用这个

AddHandler btn.Click, AddressOf [FunktionName]

回答by Vikas Bansal

Use the following code

使用以下代码

Button1.Attributes.Add("OnClick","btn_Click");

or

或者

Button1.Click += new EventHandler(btn_Click);

This is the button click method

这是按钮点击方法

protected void btn_Click(object sender, EventArgs e)
{
   do anything...        
}