'wiring-up' event handlers when creating a webform dynamically

B

bill

I'm using VS2005.

I am dynamically adding a Textbox control to a Placeholder control in the
page_load event of the form, but the event handler isn't firing. What am I
doing wrong?

Thanks
Bill



Protected Sub Page_Load....
Dim tb as new Textbox
AddHandler tb.TextChanged, AddressOf tbEventHandler
PlaceHolder1.controls.add (tb)
end sub

sub tbEventHandler
runCode
end sub
 
K

Ken Cox - Microsoft MVP

Hi Bill,

Are you providing everything that is required for the event to fire? You
might be missing Autopostback.

Here's some demo code that might get you going. Let us know if it helps?

Ken
Microsoft MVP [ASP.NET]


<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs)
' Quick sample of creating objects
' and including events using AddHandler
' Ken Cox April 9, 2006
Dim lbl As New Label
lbl.ID = "lblText"
lbl.Text = "Nothing"
PlaceHolder1.Controls.Add(lbl)

Dim lit As New Literal
lit.ID = "lit1"
lit.Text = "<br />"
PlaceHolder1.Controls.Add(lit)

Dim btn As New Button
btn.Text = "Click me"
btn.ID = "btn1"
AddHandler btn.Click, AddressOf but_click

PlaceHolder1.Controls.Add(btn)


Dim tb As New TextBox
tb.ID = "Textbox1"
tb.AutoPostBack = True
AddHandler tb.TextChanged, AddressOf tbEventHandler
PlaceHolder1.Controls.Add(tb)
End Sub

Sub tbEventHandler(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lbl As Label
lbl = Page.FindControl("lblText")
If Not IsNothing(lbl) Then
lbl.Text = "The textbox changed!"
End If
End Sub

Sub but_click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lbl As Label
lbl = Page.FindControl("lblText")
If Not IsNothing(lbl) Then
lbl.Text = "The button was clicked!"
End If
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Addhandler</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:placeholder id="PlaceHolder1" runat="server"></asp:placeholder>

</div>
</form>
</body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,743
Latest member
WoodrowMea

Latest Threads

Top