2012-08-29 84 views
0

我創建了一個自定義的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); 
} 


當用戶點擊OK按鈕事件的OnSubmit事件發生在Confrim Box上。

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.InvalidOperationException是未處理的d用戶代碼 消息=「SetFocus只能在PreRender之前和之前調用。」 來源=「的System.Web」

所以,當我動態地添加和消防自定義控件的事件,有在網絡控制錯誤。 如果我喜歡這個aspx文件添加事件,

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

沒有錯誤,做工精細。

任何人都可以幫助我動態添加事件到自定義控件嗎?
謝謝。

回答

0

最簡單的變化將是移動焦點()調用:

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再別的地方?

+0

如果我在aspx文件中添加了事件(不是動態的),它正確顯示txtResult中的文本。 – nnnn

+0

將它添加到aspx時,這些事件處理程序在創建控件時添加,通常在'Init'上。 – nunespascal

1

問題不在於在生命週期的後期加入事件的組合,以及您嘗試使用事件處理程序實現的功能。

正如錯誤中明確指出,問題是這一行:

txtResult.Focus(); 

如果您希望能夠將焦點設置到控件,您必須在InitLoad添加事件處理程序。

您可以通過使用jquery在客戶端設置焦點來解決此問題。

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

你將不得不發出這樣使用RegisterClientScriptBlock

+0

我在哪裏可以動態添加事件? – nnnn

+0

您可以在點擊上添加事件,沒有任何問題。只是不要關注他們。 – nunespascal

+0

您的意思是,我應該只在客戶端工作的Web控件(文本框..)? – nnnn