Dynamically add event to custom control (Confirm Message Box)

Posted by Nyein Nyein Chan Chan on Stack Overflow See other posts from Stack Overflow or by Nyein Nyein Chan Chan
Published on 2012-08-29T03:30:51Z Indexed on 2012/08/29 3:38 UTC
Read the original article Hit count: 495

I have created a custom cofirm message box control and I created an event like this-

[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);
}


The Event OnSubmit occurs when user click the OK button on the Confrim Box.

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


Now I am adding this OnSubmit Event Dynamically like this-
In 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>

In 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)
    {
      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
    }

The Error I got is-
System.InvalidOperationException was unhandled by user code Message="SetFocus can only be called before and during PreRender." Source="System.Web"

So, when I dynamically add and fire custom control's event, there is an error in Web Control. If I add event in aspx file like this,

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

There is no error and work fine.

Can anybody help me to add event dynamically to custom control?
Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET