Dynamically add event to custom control (Confirm Message Box)
- by Nyein Nyein Chan Chan
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.