0

Creating a dynamic button and linking it to the same event for all buttons created.

Private Sub PopulateNewOrders()
    Dim buttonNumber As Integer = 1
    For Each value In NewOrdersList
        Dim button As New Button
        button.ID = buttonNumber
        buttonNumber = buttonNumber + 1
        button.Text = "Cancel Order"
        button.CssClass = "CancelBtn"
        AddHandler button.Click, AddressOf CancelOrder_Click
        Dim Order As New TableRow
        Dim tempCell As New TableCell
        tempCell.Controls.Add(button)
        Order.Cells.Add(tempCell)
        CurrentOrderForm.Rows.Add(Order)
    Next
End Sub

Protected Sub CancelOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim button As Button = sender
        Dim int As Integer = Convert.ToInt32(button.ID)
        showButtonPressedID.text = int
    End Sub

The CancelOrder_click event never triggers. I saw someone saying it needed to be protected so I tried that and it still doesn't work.

5
  • Don't use ID's like 1,2,3 but BtnCancelOrder_1,... You also have to re-create all dynamically created controls on every postback, otherwise even't aren't triggered. Commented Jul 6, 2015 at 14:26
  • This is a method i'm calling on the Page_Load so it should be called for all instances the page is loaded; Including postback. Commented Jul 6, 2015 at 14:33
  • but is NewOrdersList also re-initialized correctly to the total-count on every postback? Where is it stored, in ViewState, Session or a Hiddenfield? Commented Jul 6, 2015 at 14:36
  • Yes, I removed the part where I pulled the List from the session as well as adding each column with values. That's all showing correctly on my webpage. The only issue i'm having is none of the buttons are being bound to my click event. If I make a jquery function to make an alert on the css class "CancelBtn" the alert goes off fine. But I need the postback to change the session which is why i'm trying to get the button event working. Commented Jul 6, 2015 at 14:40
  • Try to move the code from Page_Load to Page_Init. The former might be too late for the events. Commented Jul 6, 2015 at 14:41

1 Answer 1

1

NewOrdersList must be re-initialized correctly to the total-count on every postback. Where is it stored, in ViewState, Session or a Hiddenfield?

Yes, I removed the part where I pulled the List from the session ... This is a method i'm calling on the Page_Load so it should be called for all instances the page is loaded; Including postback.

Try to move the code from Page_Load to Page_Init. The former might be too late for the events.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.