Asp.NET DropDownList Resets SelectedIndex after Po

2020-07-07 10:31发布

问题:

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.

回答1:

Add AppendDataBoundItems="true" for dropdown list



回答2:

Make sure that your value fields are unique for each dropdown list item. If each item has the same value, it will default on index 0.



回答3:

I discovered the problem. The values being populated from my SQL statement contained values that repeated. For some reason this was causing the entire thing to malfunction in weird ways which made it so that every time I selected a ListItem the whole list would reset. By making sure no values repeated, the code started working perfectly. Thanks for everyone's help.



回答4:

Do you have Viewstate enabled or disabled? SelectedIndex is Zero based, so it were resetting I think it would be set to zero.

Also, what do the other properties of the drop down list get set to? Is the selected value correct?

Try a different browser. I had an issue with cascading drop downs where it wasn't firing/behaving correctly in Firefox.



回答5:

This happened to me when attempting to use a combined column value for the DataValueField. For example:

The stored procedure was written like this:

SELECT
    Description,
    Value1 + ',' + Value2 AS Value
FROM
    DropDownListTable

And the DataValueField used the Value field which was a combination of the Value1 and Value2 fields separated by a comma. (I also tried a pipe and no delimiter but had the same results)

 With ddl
     .DataTextField = "Description"
     .DataValueField = "Value"
     .DataSource = ds
     .DataBind() 
 End With

As soon as I used Value1 or Value2 as the DataValueField, the problem went away.



回答6:

I struggled with this too, I tried EnableViewState="true" ViewStateMode="Enabled" but it's not needed in fact, you just have to addd IsPostBack in Page_Load event. Do not forget to add IsPostBack, that is it...

if (!IsPostBack)
{
    LoadDropDown();
}


回答7:

You have to load list to DropDownList if not IsPostBack

Example code:

if (!IsPostBack)
{
   //fill here
}


回答8:

I've been experiencing the same problem, my dropdownlist stateview jump to index 1 right after a postback event from another control. My suggestion simply make sure your dropdownlist values are not empty.

Hope its help someone .... :)