简体   繁体   中英

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.

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?

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:

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. Remove IsPostBack for the part of code where you are creating the buttons is my advice.

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. With other words you should always recreate the controls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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