4

I have a dropdownlist control with a selectedindexchanged event that fires correctly. However, when you select an item from the list the index value that is returned to the selectedindexchanged event does not change; the list box pops back tot the first item in the list.

ASP DROP DOWN LIST CONTROL:

 <asp:DropDownList ID="CuisineList" runat="server" Width="100" 
    AutoPostBack = "true" onselectedindexchanged="CuisineList_SelectedIndexChanged" >
 </asp:DropDownList>

DATA BOUND TO CONTROL IN PAGELOAD EVENT:

 protected void Page_Load(object sender, EventArgs e)
 {
    //Load drop down lists for restaurant selection

    BLgetMasterData obj = new BLgetMasterData();

    var cusineList = obj.getCuisines();
    CuisineList.DataSource = cusineList;
    CuisineList.DataBind();
    CuisineList.Items.Insert(0, "Any");

SELECTEDINDEXCHANGEDEVENT:

   protected void CuisineList_SelectedIndexChanged(object sender, EventArgs e)
   {
       if (IsPostBack)
       {
           string def = this.CuisineList.SelectedItem.Value;
           //ALWAYS returns index '0'
       }
   }
2
  • How are you triggering the event? Are you using the keyboard or mouse? Believe it or not, I've run into problems where one method works and the other does not! Commented Jun 27, 2011 at 15:20
  • What is the value bound to? If the value is always zero, then selected item will be the first one in the list with value = 0 - i.e. 'Any'. Commented Jun 27, 2011 at 15:20

1 Answer 1

17

You need to put your Dropdownlist binding code under !IsPostBack() in the page_load event. like...

protected void Page_Load(object sender, EventArgs e) { 
 if(!IsPostBack)
 {
  BLgetMasterData obj = new BLgetMasterData();

  var cusineList = obj.getCuisines();
  CuisineList.DataSource = cusineList;
  CuisineList.DataBind();
  CuisineList.Items.Insert(0, "Any");
 }
}

Reason: Whenever your SelectedIndex Change Event fires, the Page_load event is called before the SelectedIndex Change event and your dropdown data rebinded, that's why your currect selection was lost.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.