简体   繁体   English

asp.net Button.Click事件未触发

[英]asp.net Button.Click event not firing

I am having an ASP.WebSite in which I have added some form controls dynamically on aspx.cs using 我有一个ASP.WebSite,在其中我使用以下方法在aspx.cs上动态添加了一些表单控件

form1.Controls.Add( " Object of Control ");

Also a have already added a button on form in aspx file using 另外一个已经使用以下格式在aspx文件中的表单上添加了按钮

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add" UseSubmitBehavior="false" />

now when I run the program it converts the Button1 into an HTML submit button as below 现在,当我运行程序时,它将Button1转换为HTML提交按钮,如下所示

<input type="button" name="Button1" value="Add" onclick="javascript:__doPostBack('Button1','')" id="Button1" />

and the form tag becomes 表单标签变成

<form name="form1" method="post" action="Add1.aspx" id="form1" enctype="multipart/form-data">

when I click the Button1 it submits the form instead of calling the function on Code Behind. 当我单击Button1时,它将提交表单,而不是在“隐藏代码”上调用该函数。

How am I able to call the method Button1_Click specified on OnClick event of Button1? 如何调用在Button1的OnClick事件上指定的Button1_Click方法?

Please Help. 请帮忙。

Have you implemented a click-event handler in codebehind? 您是否在代码隐藏中实现了点击事件处理程序?

protected void Button1_Click(Object sender, EventArgs e)
{
    Button btn = (Button)sender;
}

Button.Click Event Button.Click事件

I don't know how this question is related to your dynamic control question since Button1 is added declaratively. 由于以声明方式添加了Button1所以我不知道此问题与您的动态控制问题有什么关系。

I shoud have added the button control dynamically as follow: 我应该按如下方式动态添加按钮控件:

    b1.ID = "EDIT";
    b1.Text = "Add";
    b1.Click +=new System.EventHandler(this.Button1_Click);
    b1.Style["Position"] = "Absolute";
    b1.Style["Top"] = "10px";
    b1.Style["Left"] = "20px";
    form1.Controls.Add(b1);

It is now calling the function Button1_Click on the click event of Button1. 现在,它在Button1的click事件上调用函数Button1_Click。 I this case I have to create the function Button1_Click manually ie not just double clicking on the design page. 在这种情况下,我必须手动创建功能Button1_Click ,即不仅要双击设计页面。

the controls you are adding dynamically, you have to add it on page load. 您要动态添加的控件,则必须在页面加载时将其添加。

Then it will work fine. 然后它将正常工作。

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

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