Dynamically created webcontrol's events not firing

M

Mark Rae

Hi,

I'm sure I've done this before, but I can't get it to work today...

I'm trying to add a DropDownList into a TableCell and wire up its
SelectedIndexChanged event. I'm adding the dynamic control like this:

mtblCell = new TableCell();
mtblCell.ColumnSpan = 2;
DropDownList cmbShipping = new DropDownList();
cmbShipping.Items.Add(new ListItem("", "0"));
cmbShipping.Items.Add(new ListItem("United Kingdom", "1"));
cmbShipping.Items.Add(new ListItem("European Union", "2"));
cmbShipping.Items.Add(new ListItem("Rest of world", "3"));
cmbShipping.AutoPostBack = true;
cmbShipping.SelectedIndexChanged += new
EventHandler(cmbShipping_SelectedIndexChanged);
mtblCell.Controls.Add(cmbShipping);
mtblRow.Cells.Add(mtblCell);


I've already created the code for the event:

private void cmbShipping_SelectedIndexChanged(object sender, EventArgs e)
{
BindData();
}


It all seems to work well enough inasmuch as the DropDownList certainly does
get created in the TableCell - the resulting HTML looks like this:

<td colspan="2">
<select name="_ctl0" onchange="__doPostBack('_ctl0','')"
language="javascript">
<option value="0"></option>
<option value="1">United Kingdom</option>
<option value="2">European Union</option>
<option value="3">Rest of world</option>
</select>
</td>


When I change the selected index of the DropDownList, it does the postback
as expected. However, the cmbShipping_SelectedIndexChanged event doesn't
fire. I must be missing something totally obvious.

Any assistance gratefully received.

Mark
 
H

hashimisayed

M

Mark Rae

For these events to get wired up properly, for a DropDownList, you need
to add the controls in the OnInit() method of the page. If you add
these controls only for certain rows, I would add them but make them
invisible until you decide they need to be shown.

Sorry, I failed to mention that I'd already tried that... No matter, I found
another way to do it - thanks for the reply.
 
G

Guest

What was the solution you found? Please share

Mark Rae said:
Sorry, I failed to mention that I'd already tried that... No matter, I found
another way to do it - thanks for the reply.
 

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,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top