2

I'm creating a code in Page_PreRender function to dynamically creates some labels and buttons:

Dim btnExcludeDr As New Button()
btnExcludeDr.ID = "btnExcludeDr"
btnExcludeDr.Text = "Rate Driver"
form1.Controls.Add(btnExcludeDr)
AddHandler btnExcludeDr.Click, AddressOf Me.cmdExcludeDrv_Click

And the event which must be fired for each btnExcludeDr button is:

Protected Sub cmdExcludeDrv_Click(ByVal sender As Object, ByVal e As System.EventArgs)
   MsgBox("hello")
End Sub

But the event is not fired. Do you have any solution? thank you !

1 Answer 1

1

The best place to create your dynamic controls is in the Page_Init function that the page code-behind class provides.

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
    Dim btnExcludeDr As New Button()
    btnExcludeDr.ID = "btnExcludeDr"
    btnExcludeDr.Text = "Rate Driver"
    form1.Controls.Add(btnExcludeDr)
    AddHandler btnExcludeDr.Click, AddressOf Me.cmdExcludeDrv_Click
End Sub


Protected Sub cmdExcludeDrv_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    MsgBox("hello")
End Sub
Sign up to request clarification or add additional context in comments.

4 Comments

Page_Load or Page_Init ?? I saw you created it in Page_Load !
Method signature does not matter - the compiler only cares about Me.PreInit. I have changed the method signature label to reflect this.
I asked you because the code I have in my page contains both of these two methods (Page_Init and Page_Load) and they don't have Handles Me.PreInit !
You can use Page_event convention when you have AutoEventWireup decleration configured in aspx view. Please see this for more information msdn.microsoft.com/en-us/library/6w2tb12s.aspx

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.