ASP.Net dropdownlist not returning index on selectedindexchanged event
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 he first item in the list. Any help would be appreciated. ~susan~
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'
}
}
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
.