Asp.NET DropDownList Resets SelectedIndex after PostBack

Tyler Ferraro picture Tyler Ferraro · Apr 13, 2011 · Viewed 35.9k times · Source

After doing a lot of research online I'm still stumped by this problem. I have a page that loads the names and count of categories into a drop down list. I only do this if !(Page.IsPostBack). When AutoPostBack fires the SelectedIndex = 0. I've tried several different things. Here is my code:

PAGE

<form id="AddAssignmentForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />

<asp:UpdatePanel ID="CommentUpdate" runat="server">
<ContentTemplate>

Add Comment
<asp:DropDownList ID="ddlCategory" runat="server" Width="206" OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AutoPostBack="true" />
<asp:TextBox ID="txtName" runat="server" Width="200" />
<asp:TextBox ID="txtAbbrv" runat="server" Width="200" />
<asp:TextBox ID="txtDescription" runat="server" Width="200" Height="90" TextMode="MultiLine" />

</ContentTemplate>
</asp:UpdatePanel>
</form>

Here is the back end code.

private void Page_Load(object sender, System.EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GetCategories();
    }
}

public void GetCategories()
{
    String strSql = @"SELECT Name, Total
                        FROM MyTable";

    if (con.State == ConnectionState.Closed)
        con.Open();

    OleDbCommand cmdsql = new OleDbCommand(strSql, con);
    OleDbDataReader cmdReader = cmdsql.ExecuteReader();

    if (cmdReader.HasRows)
    {
        while (cmdReader.Read())
        {
            ddlCategory.Items.Add(new ListItem(cmdReader["Category_Name"].ToString(), cmdReader["Total"].ToString()));

        }
        ddlCategory.SelectedIndex = -1;
    }


    cmdReader.Close();
    con.Close();
}

public void FillForm(int index)
{
    ListItem item = ddlCategory.Items[index];
    txtName.Text = item.Text + " " + (Convert.ToInt32(item.Value) + 1).ToString();
    txtAbbrv.Text = item.Text.Substring(0, 1) + (Convert.ToInt32(item.Value) + 1).ToString();
}

public void ddlCategory_SelectedIndexChanged(Object sender, EventArgs e)
{
    //When I break here SelectedIndex always = 1.
    FillForm(ddlCategory.SelectedIndex);
}

I just want to be able to populate the form based on the selected index, but I can't seem to get the correct answer. Any help is appreciated.

Answer

user1799214 picture user1799214 · Dec 11, 2012

Add AppendDataBoundItems="true" for dropdown list