2010-09-24 230 views
2

我有一個ASP按鈕,我在控件的CodeBhind中創建。這裏是代碼:C#按鈕沒有觸發?

Button SubmitButton = new Button(); 

protected override void CreateChildControls() 
{ 
    SubmitButton.Text = "Submit"; 
    SubmitButton.Click += new EventHandler(SubmitButton_Click); 
} 

private void SubmitButton_Click(object sender, EventArgs e) 
{ 
    CustomTabs.CreateNewTab(); 
} 

不過,點擊事件不會觸發。它看起來像它做回發,並從未擊中事件。有任何想法嗎?

回答

2

因此,您有一些方法沒有解釋,但您是否將SubmitButton添加到頁面?某處應該是:

SomeServerControl.Controls.Add(SubmitButton); 

下,我(顯然改變命名空間)作品:

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="VS2010WEBFORMS.WebForm1" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    </form> 
</body> 
</html> 

ASPX.CS

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace VS2010WEBFORMS 
{ 
    public partial class WebForm1 : System.Web.UI.Page 
    { 
     Button SubmitButton = new Button(); 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      SubmitButton.Text = "Submit"; 
      SubmitButton.Click += new EventHandler(SubmitButton_Click); 
      form1.Controls.Add(SubmitButton); 
     } 

     private void SubmitButton_Click(object sender, EventArgs e) 
     { 
      //Something 
     } 
    } 
} 
+0

是的,我我將它添加到CreateChildControls中的頁面)方法,我發佈後的一行(假定它不重要)。我將控件移入OnLoad(),現在它可以工作。但是不正確的地方CreateChildControls()? – 2010-09-25 00:23:32

+0

您是否正在像文檔狀態那樣添加,將控件添加到頁面的代碼對於保留在您的文章中至關重要。 http://msdn.microsoft.com/en-us/library/system.web.ui.control.createchildcontrols.aspx。 – 2010-09-25 15:52:28