Today I found a weird problem, I was trying to fire a DropDownList SelectedIndexChanged event but it just didn’t work at all. After checking with other DropDownLists I have I noticed the only difference is that they are being filled using a datasource while this one is being filled manually in the backend.
Here is what I have:
<asp:DropDownList ID="DDDynAccount" runat="server"
onselectedindexchanged="DDDynAccount_SelectedIndexChanged"
AutoPostBack="true"></asp:DropDownList>
Then the Backcode when loading it:
DDDynAccount.Items.Add(new ListItem("ANY", "%"));
DDDynAccount.Items.Add(new ListItem("SELECT", "%"));
The event which is not being fired:
public void DDDynAccount_SelectedIndexChanged(object sender, EventArgs e) {
string s = ""; // I have a breackpoint here
}
If I do that, the event is never fired.
I’ve tried setting on and off the AutoPostBack. Nothing.
I’ve tried making a new control from scratch. Nothing.
I’ve also tried to call to Databind() once I’ve added its items manually but using no Datasource. Again nothing.
I have another DropDownList in the same page that works. The only difference is that that one is using a datasource. So I tried this:
List<ListItem> ds = new List<ListItem>();
ds.Add(new ListItem("ANY", "%"));
ds.Add(new ListItem("SELECT", "%"));
DDDynAccount.DataSource = ds;
DDDynAccount.DataBind();
And that will work.
My question is simple. WHY? Why cannot I fire the event if Im not using a datasource? Or there is any other problem?
I’m using .Net4 with C# in a Web Application.
Update: Ok Im sorry for this but, after checking the code wrotten here I realized a little detail, the Items I was adding manually had the same value, changing it the problem is fixed. I presume the event is not fired because the value hasnt changed, despite the “SelectedIndexChanged” should be fired not when the value is changed, but when the index is.
Both items have the same value, so as the first item is selected by default when you select the second item, the Value of the drop down list is not changed so as far as the code is concerned nothing changed and there’s nothing to do.
Having such code instead:
Will trigger the event just fine.
This is bug with .NET actually – it works only with
valueassuming it’s unique, and not with the item index.As a side note, to avoid adding more and more items each post back, wrap the adding with such statement:
Edit: was curious about you saying it worked fine with binding data source so tried for myself. Well, it fails with data source as well. With the code you posted:
Quick view of the HTML source show that the value of each option is actually its text –
ANYandSELECTand not the value you tried to assign. To assign the proper value you need such code:And you will experience the same problem as with assigning the items one by one as now the value will be the same.