2011-04-01 120 views
2

我在WebForm1.aspx.cs某網頁上的簡單的控制動態創建按鈕確定但它的事件處理程序不執行?

WebForm1.aspx

<asp:Panel ID="Panel1" runat="server"> 
</asp:Panel> 
<br /> 
<asp:Label ID="lblContent" runat="server" ></asp:Label> 

一些代碼背後:

protected void Page_Load(object sender, EventArgs e) 
{ 
    Button btn = new Button(); 
    btn.ID = "btnTest"; 
    btn.Text = "I was dynamically created"; 
    btn.Click += new EventHandler(btnTest_Click); 
    Panel1.Controls.Add(btn); 
} 

void btnTest_Click(object sender, EventArgs e) 
{ 
    lblContent.Text = "btnTest_Click: " + DateTime.Now.ToString(); 
} 

總之,當我動態的Page_Load創建一個Button(btnTest)事件並將事件處理程序btnTest_Click分配給按鈕。點擊事件,然後,當加載頁面時,我看到btnTest出現,並且當點擊它時,事件處理程序btnTest_Click被調用。好的,沒問題。

我有一個問題,雖然當我嘗試下面的場景......首先,我在設計器模式中添加一個按鈕到頁面。

<asp:Panel ID="Panel1" runat="server"> 
</asp:Panel> 
<asp:Button  ID="btnCreateDynamically" runat="server" 
      Text="Create Button Dynamically" 
       onclick="btnCreateDynamically_Click" /> 
<br /> 
<asp:Label ID="lblContent" runat="server" ></asp:Label> 

我移動代碼Page_LoadbtnCreateDynamically按鈕事件處理程序如下

protected void btnCreateDynamically_Click(object sender, EventArgs e) 
{ 
    Button btn = new Button(); 
    btn.ID = "btnTest"; 
    btn.Text = "I was dynamically created"; 
    btn.Click += new EventHandler(btnTest_Click); 
    Panel1.Controls.Add(btn); 
} 

當運行Web應用程序現在,點擊btnCreateDynamically,爲btnTest創建,但是當我點擊btnTest其事件處理程序不被調用?

爲什麼不呢? 我該如何做這項工作?

回答

2

您應該在頁面初始化事件處理程序中添加動態控件,以便正確觸發ViewState和事件。

試着這樣做:

protected void Page_Init(object sender, EventArgs e)  
{   
    Button btn = new Button();   
    btn.ID = "btnTest";   
    btn.Text = "I was dynamically created";   
    btn.Click += new EventHandler(btnTest_Click);   
    Panel1.Controls.Add(btn);  
} 
+0

如果有什麼控件是在HTTP描述上的click事件添加:/ /stackoverflow.com/questions/14338798/eventhandler-is-not-working-for-dynamic-control? – Lijo 2013-01-15 13:30:32

相關問題