Aug 30, 2010

Add Dynamic Buttons and Handle click event on server side in ASP.NET

Generally, it is required to generate buttons dynamically. Suppose user selects some items we have show all user selected item in cart where user can reject selected item. So we require to show remove button dynamically. So our object is to generate buttons dynamically and Handle click event on server side.

For this, I took literal control where buttons are to be generated. In example, when user clicks on button then he will receive message “you clicked on n”. This is handled by server side.

protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
        if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"] == "btnAsp")
                btnAsp_Click(null, null);
    private void GenerateButtons()
            StringBuilder str = new StringBuilder(); 
            for (int i = 1; i <= 10; i++)
                str.Append("<input type='button' id='btn" + i.ToString() + "' value='Button:" + i.ToString() +
                           "' onclick='javascript:__doPostBack(\"btnAsp\",\"" + i.ToString() + "\");' >"); 
            ltr.Text = str.ToString();  
    private void btnAsp_Click(object sender, System.EventArgs e)
        Response.Write("You Clicked on "+Request.Form["__EVENTARGUMENT"].ToString());  

If you have any control whose Autopostback propery = true then you need not to add following code in aspx, Only add literal control. Because It is automatically generated by .NET when Autopostback property of any control is true.

  <form id="form1" runat="server">
    <asp:Literal ID="ltr" runat="server"></asp:Literal> 
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
    <script type="text/javascript">
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;

I used __doPostBack method to fire postback and passed unique information as argument. When user clicks on button then __doPostBack method will be called, which sets two hidden control “__EVENTTARGET” and “EVENTARGUMENT” and submit the form. Now I check __EVENTTARGET on Page_Load if it is dynamic button then btnAsp_Click is called.

Hope, It helps