Nurlan
Nurlan

Reputation: 2960

dynamically created button doesn't work

The page consists linkbutton and its method:

protected void LinkButton_Click(Object sender, EventArgs e)
  {
        TableRow tr = new TableRow();
        TableCell tc = new TableCell();
        Button b = new Button(); 
        b.Text = "x";
        b.CommandArgument = "someargument";
        b.Click +=new EventHandler(this.b_Click);
        tc.Controls.Add(b);
        tc.Width = 30;
        tr.Controls.Add(tc);
        Table.Rows.Add(tr);
  }

And method:

  protected void b_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "UpdateCom",      "alert('ok');return false;", true);
        string id = (sender as Button).CommandArgument;
        // other operations...

    }

First by clicking linkbutton I create button inside table and then when I click button the b_Click method doesn't work. I even do not see javascript alert instead just page updating is occuring.

What is a problem?

Note that if I do operations inside LinkButtonClick in pageLoad method, everything is OK, button is created and b_click also works when clicking this button.

Upvotes: 0

Views: 312

Answers (1)

ecco88
ecco88

Reputation: 636

Why do you need to build the table dynamically on the button click? Could you just build it on the page Load and hide it. When the button is click show it - it can be show on the client side or server side;

I mean I would even keep it on the client side - the thing I don't like about asp.net is too many postbacks. Literally it is posting the form and its data like viewstate in hidden fields and rerendering the entire page. Seems ineffecient to me - your web server can be doing other things like serving page requests and defer this UX processing to the clients browser.

<table id="testTable" style="display: none">
  <tr>
     <td width="30px">
        <input id="b" name="b" type="button" value="someargument" text="Click Me!" onclick='alert(this.value);document.getElementById("testTable").style.display="none";' />
     </td>
  </tr>
</table>

in your link button you can add this attribute.

onclientclick='document.getElementById("testTable").style.display="inline";' /> // notice I used the single quote on the outside of the onclick.  This would display the table..

if you still need to do some server side operations on the popup2 button - you can add runat="server" and change onclick to onclientclick...

its been awhile since I used asp.net webforms so let me know if that works for you ....

Upvotes: 1

Related Questions