EDIT: Solved. An attempt to bind a DataTable to the DDL accidentally happened twice once while not checking the page’s PostBack status. Once the redundant attempt to bind was removed the problem went away. Thanks for the assistance everyone.
I have an aspx page and some code behind that feature a drop down list (ddlLocationState) or US states in alphabetical order. However no matter what item is selected, if I do ddlLocationState.SelectedItem/Value/Index it’s always “Alaska” and “0”. Every single time. Even in the SelectedIndexChange event handler.
Here’s where the DDL is declared in the aspx page (this is the only reference to it in the page):
<tr>
<td> </td>
<td class="textBlue"><label>State: </label></td>
<td>
<asp:DropDownList runat="server" ID="ddlLocationState" style="width: 250px;"/>
</td>
</tr>
Here’s the code where the contents of the DDL are setup up:
private void BindStates()
private void BindDDL()
{
//Get all state info:
// Populate a DataTable called "sdt" with two columns, name (a state)
// and "id" (a number from 0 to 49)
//Bind the DataTable "sdt":
this.ddlLocationState.DataSource = sdt;
this.ddlLocationState.DataTextField = "name";
this.ddlLocationState.DataValueField = "id";
this.ddlLocationState.DataBind();
}
Here’s some code-behind trying to get the currently selected value:
private void ddlLocationState_SelectedIndexChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("on index changed: " + dlLocationState.SelectedItem.Value.ToString());
}
Here’s where BindDDL is called:
protected void Page_Load(object sender, EventArgs e)
{
this.pnlLocationMaintenance.Visible = false;
this.LocationSortDirection = "asc";
this.LocationSortField = "address";
this.BindStates();
this.dgLocations.CurrentPageIndex = 0;
this.BindLocations();
if (!Page.IsPostBack)
{
BindDDL();
}
ddlLocationState.SelectedIndexChanged += new EventHandler(ddlLocationState_SelectedIndexChanged);
}
Why is the ddlLocationState.SelectedItem/Value/Index always the same, even in the selected index change event handler?
This will happen if you are databinding on page_load without checking to see whether you are in a postback state or not. It is my assumption from your described symptoms that this is what is happening.
In your PageLoad(…) method you need to:
if (!Page.IsPostBack)
{
BindDDL();
}