I have a ASP .Net 2 web form with EnableViewState=false for the form. Inside the form I have a dropdownlist for states dynamically populated from the OnInit. ddl is populated fine and remembering states ok. But the OnSelectedIndexChanged is not working properly. This event is fired with all but the first item. Thanks in advance. on the aspx page: --------------- <aspropDownList ID="ddlState" OnSelectedIndexChanged="ddlState_SelectedIndexChanged" runat="server" AutoPostBack="true"> </aspropDownList> On Code Behind: --------------------- protected override void OnInit(EventArgs e) { connectionString = "***********"; String commandString = "Select Top 5 LocationId,Location from Locations Where Parent='0' AND Deleted='N' Order By Location "; DataTable dataTable = ExecuteQuery(commandString); ddlState.Items.Clear(); ddlState.Items.Add(new ListItem("state/province", "0000")); foreach (DataRow myRow in dataTable.Rows) { ddlState.Items.Add(new ListItem(myRow["Location"].ToString(), myRow["LocationId"].ToString())); } base.OnInit(e); //to not completely override the base.OnInit method } protected void ddlState_SelectedIndexChanged(object sender, System.EventArgs e) { //FOR TEST Response.Write("<br>ddlState.SelectedItem.Value: " + ddlState.SelectedIndex); }
Lets say a dropdown is dynamically populated with 3 items. eg. <asp:dropdownlist id="ddl" OnSelectedIndexChanged="xxx" runat="server"> <asp:listitem>a</asp:listitem> <asp:listitem>b</asp:listitem> <asp:listitem>c</asp:listitem> </asp:dropdownlist> The OnSelectedIndexChanged event will fire for b and c not a.
the selected index on load is 0. I usually put something like "Make Selection" in my index 0. If your first state is: "AL" and it's located in index 0, it will not autopostback or selectedindexchanged becuase the index has not changed. it loads at index 0. so, by adding something like "make selection" before your first state, whenever you postback or indexchanged it will perform your action. of course you'll have to add to your code: if(DDL.SelectedIndex == 0) to not allow an indexchanged or postback if they happen to rechoose index 0 after they change to another index. put your state AL in index 1 location. PM me if ya need more info! Cheers! ps. to add another listitem to your DDL after you bind your data do this: DDL.items.insert(0, "Make Selection)