Skip to main content
 首页 » 编程设计

c#之以编程方式创建 asp :Button and attach event in SharePoint

2024年02月24日19傻小

我试图在我的 SharePoint 实例的更新面板内以编程方式创建 ASP.NET 按钮,但由于页面生命周期,我无法在按钮上附加服务器端事件。

代码如下:

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 中创建和附加按钮?

请您参考如下方法:

好的,这就是我解决它的方法,感谢所有回复,我正在寻找一种方法将事件附加到在运行时(初始化后)动态创建的按钮。希望它也适用于其他人。

<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; 
}