Asp.NET DropDownList Resets SelectedIndex after PostBack
Asked Answered
A

8

8

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.

Allayne answered 13/4, 2011 at 21:43 Comment(7)
I'm assuming you have viewstate enabled? Have you checked the request to see what the value being returned for that control is? How many items are in the dropdown?Fivespot
I'm fairly certain I've run into this issue before. Can you try making the update panel conditional and setting an async post back trigger to your DropDownLists selectedindex changed event?Dayton
Right now there are 4 items in the dropdown. I'm not sure what you mean by checking the request to see what value is being returned though. I checked the ddlCategory.SelectedIndex in SelectedIndexChanged, and it's always 1.Allayne
I changed the update panel to conditional and added the trigger. It didn't change anything. When I change the DropDownList selection it automatically jumps back to the first item in the list.Allayne
Is GetCategories() being called from anywhere else?Ibidem
No it is not. I posted all code on the page, minus a few unnecessary details that 100% do not affect the code as it is.Allayne
@Tyler what is in the request?: put a breakpoint on the postback event and see what is in Context.Request - specifically to do with that control (should be able to find it using the control's client ID). if you like post it here so I can see.Fivespot
A
4

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.

Allayne answered 14/4, 2011 at 22:43 Comment(0)
A
15

Add AppendDataBoundItems="true" for dropdown list

Abandoned answered 11/12, 2012 at 6:56 Comment(2)
this totally fixed my problem!!! i populated my drowndownlist.datasource from an arraylist. that must have confused the indices. setting appendatabounditems fixed it wooooO!O!!#Tutuila
Nice! It fixes all my dropdowns!Lavolta
A
4

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.

Allayne answered 14/4, 2011 at 22:43 Comment(0)
F
4

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.

Frink answered 15/2, 2013 at 5:52 Comment(1)
Been pulling my hair out all afternoon trying to figure this out. I had two ListItems with the same Value="-1", changing one of them solved the problem.Colatitude
I
1

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.

Ibidem answered 13/4, 2011 at 21:47 Comment(3)
ViewState is Enabled. If I disable it, then my list gets cleared on PostBack.Allayne
I tried it in Internet Explorer and I'm getting the same issue. Right now the SelectedIndexChanged isn't even being fired as the DropDownList just resets to the top selection when I change it.Allayne
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. By making sure null values became 0's, the code started working perfectly. Thanks for everyone's help.Allayne
W
1

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.

Wonderwork answered 18/7, 2014 at 14:44 Comment(0)
A
1

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();
}
Adabelle answered 4/2, 2017 at 18:5 Comment(0)
A
1

You have to load list to DropDownList if not IsPostBack

Example code:

if (!IsPostBack)
{
   //fill here
}
Audrey answered 13/11, 2017 at 12:34 Comment(0)
E
0

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 .... :)

Expatriate answered 14/2, 2013 at 9:11 Comment(1)
Please elaborate your answer. There is no point in the question that suggests that there are empty values.Kalynkam

© 2022 - 2024 — McMap. All rights reserved.