Wiring up event to a dynamically generated control

S

Sosh

Hi,

I can't seem to find much information on this. Please could someone explain
to me how to wire up events (selectedIndexChanged) to a bunch of dynamically
created controls (Dropdownlists), preferably in C#. I'm sure this should be
relatively straighforward, but can't for the life of me figure out a good
way of doing it.

Many thanks!

S
 
D

Dimitrios Toulakis

Private Sub Tester()

Dim list As New DropDownList

list.Items.Add("one")

list.Items.Add("two")

list.Items.Add("three")

list.Items.Add("four")

AddHandler list.SelectedIndexChanged, AddressOf listClick



End Sub



Protected Sub listClick(ByVal sender As Object, ByVal e As EventArgs)

'add your code here

End Sub
 
S

Sosh

Yeah thats what I'm doing at the moment (well at least the c# equivalent).
However the event handler is not being called. Heres a sumary, phDropDowns
is a placeholder, DDL SelectedIndexChanged never gets called. I have a
feeling this is something to do with the Page.IsPostBack, but how else would
you do it?

Thanks

private void Page_Load(object sender, System.EventArgs e)

{

if(!Page.IsPostBack)

{

DropDownList tempDDL = new DropDownList();

tempDDL.SelectedIndexChanged += new
System.EventHandler(DDL_SelectedIndexChanged);

tempDDL.AutoPostBack = true;

phDropDowns.Controls.Add(tempDDL);

}
}
 
S

Sosh

Hi Dimi,

I'm already setting it to true (see below) - the page is being posted back,
but the event handler is not called

Thanks
 
G

Guest

Hi Sosh,

Your problem is due to the fact that you need to rebuild all the controls
you have dynamically created on each post back. Every time the page is posted
back all the dynamically created controls are lost. So you need to recreate
them.
This should be done on or before page_load. So create a function to create
your dynamic controls and call this function on every postback. Then the
control is recreated and its event can be fired.

Kind Regards
Warren
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top