Reputation: 3834
I have a situation where I need the SelectedIndexChanged
to fire when I programatically select an item. Here is what I am doing.
I load a dropdownlist from the database on FormLoad
and I am setting the value of the drop down based on information passed in the query string like this:
if (Request.QueryString["nat"] != null)
{
ddlTriggers.ClearSelection();
ddlTriggers.Items.FindByValue(
Request.QueryString["nat"].ToString()).Selected = true;
}
This does work correctly in that it takes the id from the querystring and matches it up to a particular item in the drop down. The issue is that just by setting .selected=true
does not fire the selectedIndexChanged
event. I am trying to set some labels when the selected index is changed.
Some suggestions showed manually calling selectedIndexChanged
like this:
ddlCommonTasks_SelectedIndexChanged(ddlTriggers, EventArgs.Empty);
but then that resets the selectedIndex
and shows me the label for the 1st item in the drop down which of course doesnt help me any.
Any suggestions.
Upvotes: 1
Views: 4237
Reputation: 40497
The problem is that you are changing the selected index on post back or on page load at server. The event will not fire. What you can do is to take stuff in SelectedIndexChanged
handler and refactor it into separate method which can be called whenever you update value like:
ddlCommonTasks_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = sender as DropDownList;
PerformIndexChangedAction(ddl);
}
private void PerformIndexChangedAction(DropDownList ddl)
{
lblTest.Text=ddl.SelectedItem.Text;
}
Modify the code as follows:
var nat = Request.QueryString["nat"];
if (!String.IsNullOrWhitespace(nat))
{
ddlTriggers.ClearSelection();
ddlTriggers.Items.FindByValue(nat).Selected = true;
PerformIndexChangedAction(ddlTriggers);
}
Upvotes: 1
Reputation: 395
If I'm right in assuming that you have registered a handler for the selectedIndexChanged event, you could simply call the same function that you registered as a handler for your event.
If you've registered your handler like this:
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
You could instead define your function elsewhere, and pass that:
function handler() {
alert( "Handler for .change() called." );
}
$(".target").change(handler);
Now, in your existing code just call your handler function:
if (Request.QueryString["nat"] != null)
{
ddlTriggers.ClearSelection();
ddlTriggers.Items.FindByValue(Request.QueryString["nat"].ToString()).Selected = true;
handler();
}
Upvotes: 1