Dynamically created DropDownList not firing events or persisting viewstate

B

bryanp10

I have a page that is almost entirely dynamically created. Textboxes
and checkbox are working fine, firing events, and persistent their
state. DropDownList is giving me a major headache.

All my controls are created in CreateChildControls() for my custom
control. Here's a snippet of code:

DropDownList dd = new DropDownList();
dd.ID = "DropDown1";
if( !Page.IsPostBack )
{
//dd.DataSource = GetListItems();
//dd.DataBind();
dd.Items.Add( new ListItem("Apples", "1") );
dd.Items.Add( new ListItem("Bananas", "2") );
dd.Items.Add( new ListItem("Oranges", "3") );
int i = dd.Items.IndexOf( new ListItem( user.FruitChoice ));
if( i != -1 ) dd.SelectedIndex = i;
}
dd.SelectedIndexChanged +=new EventHandler(dd_SelectedIndexChanged);
//dd.AutoPostBack = true;
Controls.Add(dd);

The event handler never executes. My list items are not present after
a post-back. How do I persist this and get the data out of it? Why is
my event handler not firing?

I've tried re-creating the list items every time... I've tried the
autopostback obviously... I've tried explicitly assigning a control ID.
Nothing is working.

I've read a *ton* of old newsgroup posts about this very subject over
the last hour or two, but either it's a different problem or no
solution posted.

Anybody have some pointers here?

-Bryan
 
S

someone

Just out of curiosity, I note that you have the AutoPostBack line
commented out. Did you try to set the AutoPostBack to true manually
and this still happens? By default, DDLs are AutoPostBack=false.
Have you tried to debug this to see where the events are actually
going?
Just a thought,
Geek Rex
 
B

bryanp10

Yes, I have tried with AutoPastBack.
Have you tried to debug this to see where the events are actually
going?

I'm not sure what you mean by this?

Actually, it's just the SelectedIndexChanged event that is not firing.
The Load and Unload events are firing just fine. Which makes it all
the more frustrating...
 
P

Peter Rilling

Where are you building the list? Dynamically built lists need to be built
during the Init event, otherwise event will not fire.
 
B

bryanp10

I am creating the DropDownList in CreateChildControls. That certainly
seemed like the logical place to do it, given the method name. It's
where I'm creating everything else and those controls are working just
fine.
 
B

bryanp10

OK, I just tried building in the OnInit event and sure enough the
SelectedIndexChanged event fired correctly this time. Thanks for the
info Peter.
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top