Adding event to a dynamically added control added via an event - asp.net

From what I understand the best time to add a control to a page is in the OnInit event. but if you add a control via another controls event you don't have a choice it's event going to get add after the load event.
For example:
Private Sub catalog_Init(sender As Object, e As System.EventArgs) Handles Me.Init
p1.Controls.Add(New blah)
End Sub
Public Class blah
Inherits Control
Protected Overrides Sub OnInit(e As EventArgs)
Debug.WriteLine("- control oninit")
MyBase.OnInit(e)
Dim b As Button = New Button
b.Text = "link to me"
AddHandler b.Click, AddressOf blah2
Me.Controls.Add(b)
End Sub
Sub blah2(sender As Object, e As EventArgs)
Debug.WriteLine("* button event fires")
Dim b As Button = New Button
b.Text = "another button!"
AddHandler b.Click, AddressOf blah2
Me.Controls.Add(b)
End Sub
End Class
How do I get the second button's event to fire?

Related

How do I add an on click event to image button added from code behind

I am loading all images in a folder on page load by an image button from code behind.
The images are added correctly but I want to hook up an onclick event unto the image button added dynamically.
Below is my code
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
For Each strfilename As String In Directory.GetFiles(Server.MapPath("~/glypics/"))
Dim imgbtn As New ImageButton
Dim fileinfo As New FileInfo(strfilename)
imgbtn.ImageUrl = "~/glypics/" + fileinfo.Name
imgbtn.Width = Unit.Pixel(250)
Panel1.Controls.Add(imgbtn)
imgbtn.Style.Add("padding", "3px")
Next
End Sub
I am not sure what an imagebutton is? But assuming it's anything like a button you just have to add a handler, which can be done a number of ways.
Dim imgbtn As New Button
AddHandler imgbtn.Click, Sub()
'do stuff
End Sub
Or
Dim imgbtn As New Button
AddHandler imgbtn.Click, AddressOf DoClick
Private Sub DoClick(sender As Object, e As EventArgs)
'Do Stuff
End Sub
The latter is more easily removed if needed
RemoveHandler imgbtn.Click, AddressOf DoClick
Add Addhandler imgbtn.MouseClick, AddressOf imgbtn_MouseClick in your function then create the called function.
Sub imgbtn_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
'Image Button clicked...
End Sub

Click event cannot be fired on buttons created dynamically in VB.Net ASP.Net

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 !
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

Handle buttons dropdowns created dynamically

I have created few buttons and dropdowns dynamically. Code compiles fine but My event handlers are not firing? How should I handle this situation?
Protected Sub CreateAndLoadDropdowns()
Dim ddlBureauDropdowns As New DropDownList
Dim btnGo As New Button
With btnGo
.Text = "Go"
.ID = tempList2(0).MenuID
End With
AddHandler btnGo.Click, AddressOf Me.btnGo_Click
AddHandler ddlBureauDropdowns.SelectedIndexChanged, AddressOf Me.ddlBureauDropdowns_SelectedIndexChanged
phAddDropdnsHere.Controls.Add(ddlBureauDropdowns)
phAddDropdnsHere.Controls.Add(btnGo)
Next
End Sub
Protected Sub btnGo_Click(sender As Object, e As EventArgs)
End Sub
Protected Sub ddlBureauDropdowns_SelectedIndexChanged(sender As Object, e As EventArgs)
End Sub
I have moved the code to Page_init and added autopostback = true for the dropdown. The Event handlers are firing now.

re-add your handler on every postback

when the page is loaded the following code is invoke
page load
Dim products As New LinkButton
products.Text = "Products"
testPanel.Controls.Add(products)
AddHandler products.Click, AddressOf getProducts
getProducts function
Dim testDb As New Product
Dim arr As ArrayList = testDb.DbLoop()
Dim ObjList As ProductBo
Dim ID As Integer
Dim link As LinkButton
For Each ObjtList In arr
ID= ObjtList.C_Id
link = New LinkButton
testPanel.Controls.Add(New LiteralControl("<br />"))
link.ID = ID
link.Text = ObjList.Name
link.CommandArgument = CustInt
Me.testPanel.Controls.Add(link)
AddHandler link.Click, AddressOf getProductsDetails
Next ObjList
what i want to achive when the page load i link is create Products when i click on products link it invoke an event handler call getProducts. getproducts will loop in the database to fetch all record then it will creat a link for each product name when i click on the product name it should invoke another event. my problem is how can i re add control after every postback thank u
Because the links are dynamically created, you have to re-create and re-add the handler for them on each postback.
On the _init event, you have to check the state you are in (before product load or after product load), then create either the Product Load link OR the Product Details link. Key is they have to be created EVERY postback AND they have to be created before the _Load event. Typically this should be done on the _Init event.
Something along the lines of this:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
If ViewState.Item("ProductsLoaded") IsNot Nothing Then
If ViewState.Item("ProductsLoaded").ToString = "True" Then
GetProducts(Me, New EventArgs)
Else
CreateProductsButton()
End If
Else
CreateProductsButton()
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub CreateProductsButton()
Dim btnProducts As New LinkButton
btnProducts.Text = "Products"
testPanel.Controls.Add(btnProducts)
AddHandler btnProducts.Click, AddressOf GetProducts
ViewState.Item("ProductsLoaded") = False.ToString
End Sub
Private Sub GetProducts(sender As Object, e As EventArgs)
' get products list here
' and set handlers for each link
ViewState.Item("ProductsLoaded") = True.ToString
End Sub
Private Sub GetProductsDetails(sender As Object, e As EventArgs)
'get product details here
End Sub

Dynamic link button not firing in update panel

I'm dynamically adding a link button in the footer of a grid view. The grid view is wrapped in an update panel. I can get an async post back (I can tell by seeing an update progress flash), but I can't get the debug point in my click function to fire.
Private Sub gvParts_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvParts.RowDataBound
ElseIf e.Row.RowType = DataControlRowType.Footer Then
If _showPrice Then
Dim clearbutton As New LinkButton
clearbutton.ID = "btnClearCart"
clearbutton.Text = "Remove All"
ScriptManager1.RegisterAsyncPostBackControl(clearbutton)
e.Row.Cells(7).Controls.Add(clearbutton)
AddHandler clearbutton.Command, AddressOf clearButton_click
End If
End If
Private Sub clearButton_click(ByVal sender As Object, ByVal e As System.EventArgs)
ClearCart()
End Sub
try this
<dl>
Private Sub gvParts_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvParts.RowDataBound
ElseIf e.Row.RowType = DataControlRowType.Footer Then
If _showPrice Then
Dim clearbutton As New LinkButton
clearbutton.ID = "btnClearCart"
clearbutton.Text = "Remove All"
ScriptManager1.RegisterAsyncPostBackControl(clearbutton)
e.Row.Cells(7).Controls.Add(clearbutton)
AddHandler clearbutton.Command, AddressOf clearButton_click
ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(clearbutton)
End If
End If
Sorry,It's my mistake I have posted wrong code.Place the above code on OnRowCreated event of gridview
try this
Private Sub gvParts_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvParts.RowDataBound
ElseIf e.Row.RowType = DataControlRowType.Footer Then
If _showPrice Then
Dim clearbutton As New LinkButton
clearbutton.ID = "btnClearCart"
clearbutton.Text = "Remove All"
ScriptManager1.RegisterAsyncPostBackControl(clearbutton)
e.Row.Cells(7).Controls.Add(clearbutton)
AddHandler clearbutton.Command, AddressOf clearButton_click
ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(clearbutton)
End If
End If
The controls have to be added to your Controls collection prior to the page_load event. The default databinding (which fires the OnRowCreated, OnRowDataBound events) happens during the OnLoad event. Try moving your databinding code to the Page_Init function. Depending on what your databinding code looks like, this might mean you will have to implement the databinding "manually" (ie. Set the datasource and call .DataBind() in code)

Resources