简体   繁体   English

以编程方式在SharePoint中创建asp:Button和attach事件

[英]Programmatically create asp:Button and attach event in SharePoint

I'm trying to create ASP.NET buttons programmatically inside an update panel in my SharePoint instance, but because of the page life cycle, I can not attach server side events on buttons. 我正在尝试以编程方式在SharePoint实例的更新面板中创建ASP.NET按钮,但由于页面生命周期,我无法在按钮上附加服务器端事件。

Here is the code: 这是代码:

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

Is there another way to create and attach buttons in Sharepoint? 还有另一种在Sharepoint中创建和附加按钮的方法吗?

Ok here is how I solved it, Thanks for all replies, I was looking for a way to attach an event to a button that is created dynamically during runtime (after initialization). 好的,我是如何解决它的,感谢所有的回复,我正在寻找一种方法将事件附加到在运行时(初始化之后)动态创建的按钮。 Hope It works for others as well. 希望它也适用于其他人。

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

You should add your code in PreInit event, code below work good: 你应该在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");
}

You are creating dynamic controls. 您正在创建动态控件。 Your code should execute in each PageLoad event. 您的代码应该在每个PageLoad事件中执行。 Remove IsPostBack for the part of code where you are creating the buttons is my advice. 删除IsPostBack是您创建按钮的代码部分是我的建议。

If you don't do this, you will create the controls, but each time when PageLoad event occurs, your control will be deleted and the application will not follow your events. 如果不这样做,您将创建控件,但每次发生PageLoad事件时,您的控件都将被删除,应用程序将不会跟踪您的事件。 With other words you should always recreate the controls. 换句话说,您应该始终重新创建控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM