将事件动态添加到自定义控件(确认消息框)

本文关键字:确认 消息 自定义控件 事件 动态 添加 | 更新日期: 2025-02-18 03:19:28

我创建了一个自定义的cofirm消息框控件,并创建了这样的事件-

[Category("Action")]
[Description("Raised when the user clicks the button(ok)")]
    public event EventHandler Submit;
protected virtual void OnSubmit(EventArgs e) {
     if (Submit != null)
        Submit(this, e);
}


当用户单击Confrim Box上的OK按钮时,会发生Event OnSubmit。

void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
    OnSubmit(e);
}


现在我像这样动态地添加这个OnSubmit事件-
在aspx-

<my:ConfirmMessageBox ID="cfmTest" runat="server" ></my:ConfirmMessageBox>
    <asp:Button ID="btnCallMsg" runat="server" onclick="btnCallMsg_Click" />
    <asp:TextBox ID="txtResult" runat="server" ></asp:TextBox>

在cs-

protected void btnCallMsg_Click(object sender, EventArgs e)
{
  cfmTest.Submit += cfmTest_Submit;//Dynamically Add Event
  cfmTest.ShowConfirm("Are you sure to Save Data?");  //Show Confirm Message using Custom Control Message Box
}
    protected void cfmTest_Submit(object sender, EventArgs e)
        {
          //..Some Code..
          //..
          txtResult.Text = "User Confirmed";//I set the text to "User Confrimed" but it's not displayed
          txtResult.Focus();//I focus the textbox but I got Error
        }

我得到的错误是-
用户代码未处理System.InvalidOperationExceptionMessage="SetFocus只能在PreRender之前和期间调用。"Source="System.Web"

因此,当我动态添加并激发自定义控件的事件时,Web控件中会出现错误。如果我像这样在aspx文件中添加事件,

<my:ConfirmMessageBox ID="cfmTest" runat="server" OnSubmit="cfmTest_Submit"></my:ConfirmMessageBox>

没有错误,工作正常

有人能帮助我将事件动态添加到自定义控件中吗
谢谢

将事件动态添加到自定义控件(确认消息框)

问题不在于在生命周期后期添加的事件与您试图使用事件处理程序实现的目标的组合。

正如错误明确指出的那样,问题出在这条线上:

txtResult.Focus();

如果希望能够将焦点设置为控件,则必须在InitLoad上添加事件处理程序。

您可以通过使用jquery在客户端设置焦点来解决这个问题。

var script = "$('#"+txtResult.ClientID+"').focus();";

您必须使用RegisterClientScriptBlock来发出此消息。

最简单的更改是移动焦点()调用:

bool focusResults = false;
    protected void cfmTest_Sumit(object sender, EventArgs e)
    {
      txtResult.Text = "User Confirmed";
     focusResults = true;
    }
    protected override void OnPreRender(EventArgs e)
    {
       base.OnPreRender(e);
        if(focusResults)
           txtResult.Focus();
    }

您确定没有在其他地方再次设置txtResult.Text吗?