I used to think my c# programming wasn’t too bad, but today I am seriously questioning my head, something so small is defeating me…
I am trying to get a DropDownList to behave but we are not getting on today. I have a simple DropDownList in an ascx control which is dynamically loaded into an aspx page
<asp:DropDownList ID="ddl_SortBy" runat="server" AutoPostBack="true">
<asp:ListItem Value="0">Sort Alphabetically A to Z</asp:ListItem>
<asp:ListItem Value="1">Sort Alphabetically Z to A</asp:ListItem>
</asp:DropDownList>
and some code behind..
private short SortBy = 0;
protected void Page_Load(object sender, EventArgs e)
{
this.ddl_SortBy.SelectedIndex = -1;
this.ddl_SortBy.SelectedIndexChanged += new EventHandler(ddl_SortBy_SelectedIndexChanged);
if (!IsPostBack)
SearchDirectory();
}
public void ddl_SortBy_SelectedIndexChanged(object sender, EventArgs e)
{
SortBy = Convert.ToInt16(this.ddl_SortBy.SelectedItem.Value);
SearchDirectory();
}
I can never get the first item to trigger the selected index change event – as the SearchDirectory() function is not called. I can understand that it’s possibly the case that when the control loads the first item IS selected so when selecting, the index isn’t actually changing.
I have tried setting the selected item index to -1, and ClearSelection() on page load, but no luck.
Any ideas? Thanks
You are always resetting the
SelectedIndexto -1 on every postback:So put that also in the postback-check: