这是我的Page1.aspx代码:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Panel ID="Panel1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Panel>
</asp:Content>
这是我的Page1.aspx.cs代码
public partial class Page1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == true)
{
btn_Click(sender, e);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Dynamic button";
btn.Click += btn_Click;
Panel1.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Response.Redirect("../Page2");
}
}
从这段代码中,当&#34; Button1&#34;单击它应该创建一个新按钮&#34; btn&#34;当&#34; btn&#34;点击它,它应该转到其点击功能的网址(即btn_Click())。但是当我点击&#34; Button1&#34;它没有执行&#34; Button1_Click()&#34;但是&#34; btn_Click()&#34;。我该怎么办?
答案 0 :(得分:0)
if (IsPostBack == true)
可以成为
if (IsPostBack)
然后
Response.Redirect("../Page2");
可以成为
Response.Redirect("~/Page2");
在aspx检查中,您有:
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click"></asp:Button>
此外,您可以在后面的代码中绑定点击(例如OnLoad):
Button1.Click + = Button1_Click;
并解开绑定:
Button1.Click - = Button1_Click;