为动态创建的按钮asp.net创建onClick事件

时间:2016-03-14 18:14:03

标签: asp.net button dynamic click

这是我的.aspx页面

<asp:Panel ID="Panel1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <asp:Label ID="Label1" runat="server"></asp:Label>
</asp:Panel>    

这是我的aspx.cs页面

public partial class Test : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        Button button2 = new Button();
        button2.Text = "Dynamic Button";
        button2.Click += new EventHandler(button2_Click);
        Panel1.Controls.Add(button2);
    }

    void button2_Click(object sender, EventArgs e)
    {
        Label1.Text = "working";
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

&#34; button2&#34;点击甚至不起作用。我也尝试过:

button2.Click += button2_Click;

但这似乎也不起作用。 如果我将代码放在&#34; Page_Load&#34;功能,它的工作原理。但是我希望在点击第一个按钮(即Button1)时将动态按钮添加到页面中。

如何使这项工作?

2 个答案:

答案 0 :(得分:0)

也许你可以在aspx页面中同时拥有两个按钮,并为每个按钮定义了onclick属性事件。只需将button2的可见性保持为false,然后单击button1即可使button2的可见性为true。这不是一般答案。这是您的问题的快速转变

答案 1 :(得分:0)

您可以将PlaceHolder添加到Panel:

<asp:Panel ID="Panel1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <asp:PlaceHolder ID="ph" runat="server" />
</asp:Panel>

并在其中插入按钮,确保在每次回发时重新创建它:

protected void Button1_Click(object sender, EventArgs e)
{
    CreateDynamicButton();
    ViewState.Add("Button2", "Yes");
}

protected void CreateDynamicButton()
{
    Button button2 = new Button();
    button2.ID = "button2";
    button2.Text = "Dynamic Button";
    button2.Click += new EventHandler(button2_Click);
    ph.Controls.Clear();
    ph.Controls.Add(button2);
}

protected override void CreateChildControls()
{
    base.CreateChildControls();
    if (ViewState("Button2") == "Yes")
    {
        CreateDynamicButton();
    }
}

void button2_Click(object sender, EventArgs e)
{
    Label1.Text = "working";
}