views:

40

answers:

2

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

Thanks in advanc.

+1  A: 

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");
}
Tarek El-Mallah
is it possible to call OnPreInit() in another Event ?
Kubi
You don't call OnPreInit - the web part infrastructure calls it on your behalf. http://nishantrana.wordpress.com/2009/02/14/understanding-web-part-life-cycle/
Ryan
you just override OnPreInit, not call it.
Tarek El-Mallah
@tarek my problem was adding buttons during runtime, after the initialization...
Kubi
@Kubi I think you can't, try below solution of @Kubi
Tarek El-Mallah
A: 

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;
}
Kubi
Don't forget to accept your own answer as correct (by pressing on a tick)
abatishchev