2010-06-03 38 views
3

我開始編碼一些複雜的事物,然後意識到我的事件處理程序不起作用,所以我使用事件處理程序簡化了一個按鈕。請看下面的代碼,也許你可以告訴我爲什麼它不會觸發?我的webpart事件處理不會在SharePoint中觸發

using System; 
using System.Collections.Generic; 
using System.Runtime.InteropServices; 
using System.Web.UI; 
using System.Web.UI.WebControls.WebParts; 
using Microsoft.SharePoint; 
using System.Web.UI.WebControls; 
namespace PrinterSolution 
{ 
    [Guid("60e54fde-01bd-482e-9e3b-85e0e73ae33d")] 
    public class ManageUsers : Microsoft.SharePoint.WebPartPages.WebPart 
    { 
     Button btnNew; 


     protected override void CreateChildControls() 
     { 
      btnNew = new Button(); 
      btnNew.CommandName = "New"; 
      btnNew.CommandArgument = "Argument"; 
      btnNew.Command += new CommandEventHandler(btnNew_Command); 
      this.Controls.Add(btnNew); 
     } 

     void btnNew_Command(object sender, CommandEventArgs e) 
     { 
      ViewState["state"] = "newstate"; 
     } 



     //protected override void OnLoad(EventArgs e) 
     //{ 
     // this.EnsureChildControls(); 
     //} 

    } 
} 

回答

2

我有類似的問題。在我的情況下,按鈕包含在面板中,雖然父控件上的按鈕正常工作,但子控件Panel控件上的按鈕卻沒有。

事實證明,你需要調用EnsureChildControls在子面板的OnLoad方法來確保CreateChildControls被稱爲足夠早在life cycle of the page使控件可以對事件做出響應。這在this answer here中簡要描述,這是我發現我的問題的解決方案。

根據這一指令,我只是下面的代碼添加到我的面板控制:

protected override void OnLoad(EventArgs e) 
    { 
     EnsureChildControls(); 
     base.OnLoad(e); 
    } 

我注意到,有似乎是一個很大的混亂有關此問題的論壇,以便證明這個作品,我添加跟蹤我的代碼。以下是案例之前和之後的結果。請注意,Survey list creating child controls的位置從PreRender事件內移動到Load事件中。

前:

Before making the change to call EnsureChildControls in the OnLoad override

後:

After making the change to call EnsureChildCOntrols in the OnLoad override which shows the child controls being created in the correct place in the page life cycle

相關問題