[karsten samaschke]

ASP.NET daily. Or weekly.

How to handle dynamically created buttons in ASP.NET

This problem is very often discussed in Newsgroups:

How can I handle clicks on dynamically created buttons?

Ususally you're adviced to declare the buttons in the CodeBehind of your aspx-Page. But this is not the way to create buttons (or other controls) dynamically, because there is no real dynamic in the process.

If you create buttons on-the-fly, you do not have the possiblity to use their eventhandlers. Take a look at the following codesnippet:

Dim objButton As New Button
objButton.Text = "Click me!"
Page.Controls.Add(objButton)

Once you added the button to your page, you don't have a chance to react on the click.

Really?

What, if there was a chance to react on the button's click? Even if this reaction was not handled by the button's eventhandler? Look at this:

' Registering a hidden field in the Page
Page.RegisterHiddenField(Me.UniqueID & _
   "_buttonClicked", "")

' Defining the Button
Dim objButton As New Button
objButton.Text = "Click me!"

' Here's the trick... :)
objButton.Attributes.Add("onClick", _
   "document.forms[0]." & Me.UniqueID & _
   "_buttonClicked.value='" & _
   objButton.UniqueID & "';document.forms[0].submit();")

' Adding the button to the page
Page.Controls.Add(objButton)

What was done here? Really simple: We added a JavaScript to the button which sets a value in the hidden field. On PostBack we're able to track this hidden field and detect, wheter the button was clicked or not:

' Use this snippet on PostBack
If Page.IsPostBack Then
   If Request.Item(Me.UniqueID & _
      "_buttonClicked").Length > 0 Then
      Response.Write("Button " & _
         Request.Item(Me.UniqueID & _
            "_buttonClicked") & _
            " was clicked!")
   End If
End If

On this place you can add your own handling of the event or raise another event. In any case: You are able to track, wheter the button was clicked or not. Problem solved. :)

Comments

Martina said:

Thanks for that but I have a dropdown and on the onclick of a Button I want the page to go to a URL in the dropdown(its value is held in the Value of the option) but I'm not sure how to do this in the attributes section below. Any suggestions would be great?


Dim drpEditControl = New DropDownList()
Dim btnGo = New Button()

--then code to populate dropdown

btnGo.Attributes.Add("onClick", "")

'add dropdown list to the page
Me.Controls.Add(drpEditControl)
Me.Controls.Add(btnGo)
# March 24, 2003 4:00 AM

Mike Hnatt said:

But, using this method the form validation is ignored and thus only works if you are not validating. Any ideas?
# September 8, 2003 5:34 PM

Mike said:

There's a much more elegant way to handle events in dynamically created controls:

Dim objButton As New Button
objButton.Text = "Click me!"
objButton.ID = "ButtonID"
AddHandler objButton.Click, AddressOf Button_Click()

Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim sButton As String = CType(sender, Button).ID
templabel.Text = "The Button " & sButton & "was clicked."
End Sub
# September 23, 2003 9:34 AM

Valerio said:

But this way works only if the button is added in the sub Page_load. If you add the button in other subs, you are not be able to handle events of the button, because on postback the button is not present in the page.
# November 4, 2003 6:14 AM

John said:

For C# users, use objButton.Click+=new System.EventHandler(this.btnChecklist_Click);
# December 17, 2003 11:53 PM

kk said:

How to get the botton ID in 'this.btnChecklist_Click'
# March 24, 2004 12:51 AM

Philip Johnston said:

After working with the AddHandler, I would have to agree with the original article. I would also say that Microsoft has really missed the boat when it comes to using Dynamic Controls and the AddHandler. The proof of this becomes apparent when you begin nesting controls within controls.
# May 4, 2004 3:29 PM

Brandon said:

What if I create more than one dynamic buttons?
Then I can't use uniqueID, right? How should I distinguise which button has been clicked?
# June 15, 2004 9:41 AM

Brandon said:

I'm sorry i've got it..it was dumb question..
# June 15, 2004 10:00 AM

Spencer said:

I have tried using the second method in c#=

Dim objButton As New Button
objButton.Text = "Click me!"
objButton.ID = "ButtonID"
AddHandler objButton.Click, AddressOf Button_Click()
------------------------------------------
Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim sButton As String = CType(sender, Button).ID
templabel.Text = "The Button " & sButton & "was clicked."
End Sub
------------------------------------------

My code looks like this:
-------------------------------------------
Button btnSubmitScore = new Button();

btnSubmitScore.Text = "Submit";

btnSubmitScore.Click += new System.EventHandler(this.btnMenu_Click);

dgPhrase.Items[iItems].Cells[3].Controls.Add(btnSubmitScore);
------------------------------------------
It appears that btnMenu_Click never gets called. The page simply does a post back. btnMenu_Click should redirect to a new page. Any ideas about what I am doing wrong?

# June 28, 2004 1:28 PM

Steven said:

I have the following in c# which fails ever to register the eventhandler (never gets called). Is someone saying that this code needs to be on Page_Load ?

...
btnAddFile.Text = "Add File";

// add the button
cell.Controls.Add(btnAddFile);

btnAddFile.Click += new System.EventHandler(this.btnAdd_Click);
....
# July 14, 2004 11:15 AM

Prashanth said:

No, I do not think you need to have the code in the Page Load event. Here's a sample code which creates a DropDownList (adds it to the table cell of an asp table) and a Button (which text Click - adds this to the Page) when the Button on the page is clicked. When you click the Click button after adding the controls on fly the Label at the bottom gets displayed with the Selected text on the dropdown.

Enjoy Coding.

***********HTML****************************
<asp:Table ID="tbl1" Runat="server" Width="200px">
<asp:TableRow ID="tr1" Runat="server" Width="100%">
<asp:TableCell ID="tc1" Runat="server" Width="50%"></asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="trlink" Runat="server" Width="100%">
<asp:TableCell ID="tclink" Runat="server" Width="50%">
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 224px" runat="server"
Width="312px">Label</asp:Label>
<asp:Label id="Label2" style="Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 256px" runat="server"
Width="312px">Label</asp:Label>

***********************************************


******Code Behind ****************************

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.DropDownList DropDownList1;
protected System.Web.UI.WebControls.Table tbl1;

private void Page_Load(object sender, System.EventArgs e)
{
if(IsPostBack)
{
CreateButtons();}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//

InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
CreateButtons();
}

private void btn_Click(object sender, EventArgs e)
{
Label1.Text = "Button was clicked";
}

private void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl1 = new DropDownList();
ddl1 = (DropDownList)Page.FindControl("Form1").FindControl("tbl1").FindControl("tr1").FindControl("tc1").FindControl("ddl1");
if(ddl1 != null){Label2.Text = ddl1.SelectedItem.Text;}
}

private void CreateButtons()
{
DropDownList ddl = new DropDownList();
ddl.Items.Add("1");
ddl.Items.Add("2");
ddl.Items.Add("3");
ddl.ID = "ddl1";
DropDownList ddl1 = new DropDownList();
ddl1 = (DropDownList) Page.FindControl("Form1").FindControl("tbl1").FindControl("tr1").FindControl("tc1").FindControl("ddl1");
if(ddl1 == null){
Page.FindControl("Form1").FindControl("tbl1").FindControl("tr1").FindControl("tc1").Controls.Add(ddl);
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);}

Button btn1 = new Button();
btn1 = (Button)Page.FindControl("Form1").FindControl("btn1");
if(btn1 == null){
Button btn = new Button();
btn.Text = "Click";
btn.ID = "btn1";

Page.FindControl("Form1").Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);}
}


}


***************************************************
# July 16, 2004 5:03 PM

Zac said:

when a button is clicked on i want it to go to another page. how do i do this?
# July 21, 2004 9:52 AM

anthony said:

then use validation controls on client side before postback
# July 23, 2004 3:31 PM

anthony said:

I found out that in order for the original code to work, you must add an ID to the button after you created it, e.g.
objButton.ID = "butTest"
# July 23, 2004 3:45 PM

maha said:

hi,

let me know how to add button click event dynamically in placeholder.

In my program , i created a link button. after clicking the linkbutton some controls(textbox,label ,button) are dynamically added to the form.

In that dynamic controls i want to add button click.

protected void LinkButton1_Click(object sender, EventArgs e)

   {

Button b1 = new Button();

b1.ID = "button";

PlaceHolder1.Controls.Add(b1);

      b1.Click+=new EventHandler(this.b1_Click);

           }

private void b1_Click(object sender, EventArgs e)

   {

      labe1.text="welcome";

   }  

In the code program does't handle the button click event.

# December 20, 2007 3:03 AM

Tejaswini S said:

hi,

i have two dropdown lists namely SDU & support

Format is:

SDU (dropdown list)                    Support(dropdown list)

                                   Add(button)

when i click on the add button i want the same two drop down lists i.e., SDU& Support to be displayed

like:

SDU (dropdown list)                    Support(dropdown list)

SDU (dropdown list)                    Support(dropdown list)

                                   Add(button)

and so on...................

using asp, how can i code it?

Please help me

its urgent

# March 7, 2008 1:26 AM

Philipp Küng said:

I know I'm quite late for this post. But is there a possibility to use this this way in C#, because in C# I don't have a

HttpRequest.Item()

Method. And after some search with no results I hope know you coult help me.

# April 18, 2008 12:22 PM

sandeep_sfx said:

how do i validate textbox generated dynamically for only numbers.

# September 10, 2008 7:54 AM

sandeep_sfx said:

hi tejaswini  s,

Try this..

Add_Click()

{

DropDownList DD1 = new DropDownList();

foreach(ListItem LI in SDU.Items)

{

 DD1.Items.Add(LI);

}

DropDownList DD2 = new DropDownList();

foreach(ListItem LI in Support.Items)

{

 DD2.Items.Add(LI);

}

}

//Thanks n regard

# September 10, 2008 8:01 AM

shoyeb said:

Dim objButton As New Button

objButton.Text = "Click me!"

objButton.ID = "ButtonID"

AddHandler objButton.Click, AddressOf Button_Click()

Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

Dim sButton As String = CType(sender, Button).ID

templabel.Text = "The Button " & sButton & "was clicked."

End Sub

i have tried the code

but error generetd telling

"Argument not specified for parameter 'e' of 'Public Sub Button_Click(sender As Object, e As System.EventArgs)'."

# October 16, 2008 6:59 AM

Koen De Win said:

@ Shoyeb

Had the same error

Lose the parentheses at button_click

so it will be

AddHandler objButton.Click, AddressOf Button_Click

The rest should work

# October 22, 2008 8:31 AM

UrEnjoy said:

See Alternate and easy way to generate dynamic buttons:

urenjoy.blogspot.com/.../add-dynamic-buttons-and-handle-click.html

# February 18, 2009 12:06 AM

Maya said:

hi,

I want to add more then 1 link buttons dynamically. i added them using the for loop .so how i will come to knw that which link button is clicked???. on every linkbutton click i want to display different images in the pop up window.

# April 3, 2009 2:19 AM

Oli said:

This post is quite old, but the following information might be useful to somebody.

Add your controls in the OnInit method by overriding it, then your button event will be executed:

protected override void OnInit(EventArgs e)

{

// Add your button dynamiccaly here base.OnInit(e);

}

Information found on: support.microsoft.com/.../en-us

# July 3, 2009 1:45 PM

anju said:

Hi

I am dynamically adding link buttons to my page using  for loop. I know the count of link buttons created only at run time. Depending on link button clicked i want to display different messges. But how do i know which link button was clicked

please can anyone help me. its really urgent

# September 25, 2009 1:18 AM

Elia said:

Hi there,

I need to add buttons with event handles dynamically by pressing another button -let's say static one-. How this dream can be achieved?!

I'd appreciate solving it!

# December 3, 2009 1:06 AM

ankitkshah said:

hiii...

i have following code

Dim d As New Button

d.Text = "add"

d.Attributes.Add("onclick", "")

i want to page is redirect to another page on click event of add... what should i do???

Please reply...

# March 12, 2010 12:07 AM

Mitesh SVIT said:

hi i beginners in asp.net programming site .

i have query about to creating button at run time .

  Actually my requirement is i will have random number of button ,i need to create  on  page all button and onclicking any one of button it should give its ID value ...

# April 26, 2010 6:08 PM

Jones said:

thanks, helpful post.

# July 23, 2010 1:45 AM

BP said:

2011 and this post is still coming in handy.  

# February 23, 2011 3:50 PM

Martin said:

@anju and others re picking up which button was clicked:

In your loop that dynamically creates the buttons, give each a unique ID such as btnClick_1, btnClick_2...

The event sub should take a "sender as Object" parameter, just like the event handlers for controls you create at design time.

Then you can pick up the loop number from the clicked button with the following line:

buttonID = Val(CType(sender, Button).ID.Split("_")(1))

(I'm using VB here, but the same principle will apply in C - split the string at the "_" or whatever delimiter you use when you assign the button IDs)

# May 6, 2011 1:04 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)