【问题标题】:Add click event handler to a button that was dynamically created in another class将单击事件处理程序添加到在另一个类中动态创建的按钮
【发布时间】:2018-09-23 04:50:22
【问题描述】:

我在与我希望按钮交互的 aspx 页面后面的代码不同的类中创建了一个确认按钮。

基本上,假设我有这个 Confirmation 类:

public class Confirmation
{
    public void GenerateButtons()
    {
        Button btnConfirm = new Button();

        btnConfirm.Text = "Confirm";
        btnConfirm.CommandName = "Variable1,Variable2,Variable3";

        _Default def = new _Default();
        btnConfirm.Click += new EventHandler(def.btnConfirmBook_Click);
    }
}

上面的代码是代码的一个非常释义的版本。但是会循环生成多个按钮并添加到表格中。该表显示在下面提到的 Default.aspx 页面上。对于表中的每一行,CommandName 属性的值包含不同的值。

我正在使用的 aspx 页面是 Web Forms .NET Web 应用程序中的默认页面。

我希望在单击这些按钮之一时触发的事件被带回到 Default.aspx 页面 (Default.aspx.cs) 后面的代码中。

这是我在 Default.aspx.cs 中的内容:

public void btnConfirm_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;

    DisplayConfirmation(btn.CommandName);
}

protected void DisplayConfirmation(string result)
{
    // I split result and manipulate it as necessary to get a confirmationText string

    pnlMainPanel.Visible = false; // This is where it throws NullReferenceException
    pnlConfirmationPanel.Visible = true;

    lblConfirmationText.Text = confirmationText;
}

我假设它在尝试更改面板的可见性时抛出 NullReferenceException,因为我创建了 _Default 类的新实例,以便我可以在第一个代码 sn-p 的最后一行中设置 EventHandler。

但我不知道如何让它工作。

【问题讨论】:

  • 不是创建_Default 类的新实例,您不能将_Default 类实例作为GenerateButtons 方法的引用传递吗?

标签: c# asp.net webforms


【解决方案1】:

你猜对了。不要创建 _Default 类的新实例。

ASPX:

<form id="form1" runat="server">
<div>
    <asp:Panel ID="Panel1" runat="server">
        make me invisible;
    </asp:Panel>
</div>
</form>

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    GenerateButtons();
}

public void GenerateButtons()
{
    AnotherClass anotherClass = new AnotherClass(this);
}

public void btnConfirmBook_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    DisplayConfirmation();
}

protected void DisplayConfirmation()
{
    Panel1.Visible = false;
}

另一个类:

public class AnotherClass
{
    public AnotherClass(Default def)
    {

        Button btnConfirm = new Button();

        btnConfirm.Text = "Confirm";
        btnConfirm.CommandName = "Variable1,Variable2,Variable3";
        def.Form.Controls.Add(btnConfirm);

        btnConfirm.Click += new EventHandler(def.btnConfirmBook_Click);

    }
}

【讨论】:

  • 10/10 伙计,谢谢。我最初尝试做这样的事情,但我无法让它工作。不知道您可以将现有实例作为this 传递。干杯
猜你喜欢
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多