Repost: Why can't I add an event from another event handler?

J

James P

TextBox txtCondition;
DropDownList ddlLevels;
DropDownList ddlPriorities;
Button btnSearch;

private void btnSearch_Click(object sender, EventArgs e)
{
if (ddlLevels.SelectedItem.Text == "1")
{
ddlPriorities.SelectedIndexChanged += new
EventHandler(this.Priority1handler)
ddlPriorities.AutoPostBack = true;
}
}

private void Priority1handler(object sender, EventArgs e)
{
// Do something.
}

The Auto Post Back works. But the event handler never gets called.

James
 
H

Hans Kesting

James P said:
TextBox txtCondition;
DropDownList ddlLevels;
DropDownList ddlPriorities;
Button btnSearch;

private void btnSearch_Click(object sender, EventArgs e)
{
if (ddlLevels.SelectedItem.Text == "1")
{
ddlPriorities.SelectedIndexChanged += new
EventHandler(this.Priority1handler)
ddlPriorities.AutoPostBack = true;
}
}

private void Priority1handler(object sender, EventArgs e)
{
// Do something.
}

The Auto Post Back works. But the event handler never gets called.

James

If you attach an eventhandler, this will only work on *this* request. You
will
have to re-attach on every request. So what happens is this:
After a click on the button, you attach the eventhandler. But, as the value
of the dropdown didn't change, it is not called.
When you do change the dropdown, the button isn't clicked, so the
eventhandler
is not attached.
If you manage to do both, then you could have problems with the order in
which the
events are handled: it could happen that the "SelectedIndexChanged" is fired
first
(but, as there is no handler attached, nothing happens) and then the
"OnClick".

What you should do:
attach all event handlers everytime (in Page_Load)
in the eventhandler itself check for special conditions (level == 1? skip!)

Hans Kesting
 
J

James P

Makes sense. Thanks.
James
Hans Kesting said:
If you attach an eventhandler, this will only work on *this* request. You
will
have to re-attach on every request. So what happens is this:
After a click on the button, you attach the eventhandler. But, as the value
of the dropdown didn't change, it is not called.
When you do change the dropdown, the button isn't clicked, so the
eventhandler
is not attached.
If you manage to do both, then you could have problems with the order in
which the
events are handled: it could happen that the "SelectedIndexChanged" is fired
first
(but, as there is no handler attached, nothing happens) and then the
"OnClick".

What you should do:
attach all event handlers everytime (in Page_Load)
in the eventhandler itself check for special conditions (level == 1? skip!)

Hans Kesting
 

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

Top