2010-10-19 22 views
1

我試圖在我的SharePoint實例的更新面板中以編程方式創建ASP.NET按鈕,但由於頁面生命週期,我無法在服務器端按鈕上附加事件。以編程方式在SharePoint中創建asp:按鈕並附加事件

下面是代碼:

TableCell tcellbutton = new TableCell(); 
b.Click += new EventHandler(b_Click); 
b.CausesValidation = true; 
tcellbutton.Controls.Add(b); 
tr.Cells.Add(tcellbutton); 
table.Rows.Add(tr); 
panel1.Controls.Add(table); 

void b_Click(object sender, EventArgs e) 
{ 
    string studentnumber = (sender as Button).ID.ToString().Substring(3, (sender as Button).ID.ToString().Length - 3); 
    TextBox t = panel1.FindControl("txt" + studentNumber) as TextBox; 
} 

是否有另一種方式來創建和SharePoint連接按鈕?

+0

修復您的格式並放入完整的代碼片段(例如,您將控件添加到哪個方法或事件中 - 這幾乎肯定是問題,並且您已將其遺漏),它可能會讓您更多一點幫幫我。 – Ryan 2010-10-20 08:03:38

+0

嗨瑞安,我的問題在這裏基本上是我不能附加事件控件在運行時,它必須在頁面初始化,我可以重寫和運行相同的代碼沒有任何錯誤,但我的問題是,如果它是在運行時可用以及.. – Kubi 2010-10-20 08:39:43

回答

2

確定這裏是我如何解決它,感謝所有的答覆,我一直在尋找一種方式將事件附加到在運行期間(初始化後)動態創建的按鈕。希望它也適用於其他人。

<script type="text/javascript"> 
    function ButtonClick(buttonId) { 
     alert("Button " + buttonId + " clicked from javascript"); 
    } 
</script> 

protected void Button_Click(object sender, EventArgs e) 
{ 
    ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>"); 
    Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked"); 
}  

private Button GetButton(string id, string name) 
{ 
    Button b = new Button(); 
    b.Text = name; 
    b.ID = id; 
    b.Click += new EventHandler(Button_Click); 
    b.OnClientClick = "ButtonClick('" + b.ClientID + "')"; 
    return b; 
} 
+0

不要忘記接受你自己的答案是正確的(通過按打勾) – abatishchev 2010-10-20 10:20:48

1

你應該PreInit事件中添加代碼,下面工作的良好代碼:

protected override void OnPreInit(EventArgs e) 
{ 
    base.OnPreInit(e); 
    Button bb = new Button(); 
    bb.Click += new EventHandler(bb_Click); 
    bb.CausesValidation = true; 
    bb.ID = "button1"; 
    Panel1.Controls.Add(bb); 
} 

private void bb_Click(object sender, EventArgs e) 
{ 
    Response.Write("any thing here"); 
} 
+0

是否有可能在另一個事件中調用OnPreInit()? – Kubi 2010-10-19 10:37:48

+1

您不要調用OnPreInit - Web部件基礎結構代表您調用它。 http://nishantrana.wordpress.com/2009/02/14/understanding-web-part-life-cycle/ – Ryan 2010-10-20 08:06:50

+0

你只是重寫OnPreInit,而不是調用它。 – 2010-10-20 11:09:26

1

您正在創建動態控件。您的代碼應該在每個PageLoad事件中執行。 刪除IsPostBack您創建按鈕的代碼部分是我的建議。

如果你不這樣做,你將創建控件,但每次當PageLoad事件發生的時候,你的控制將被刪除,應用程序將不會跟隨你的事件。換句話說,你應該總是重新創建控件。

相關問題