1

As advised here ASP.NET Response.Redirect(Request.RawUrl) doesn't work I did put autopostback = true on a dropdown list to reload my page.

But after reloading it resets also the selected item to first one.

How to keep my previous value before reloading the page then ? I thought autopostback would do that job ?

Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487

5 Answers5

10

Make sure you're not repopulating the dropdown list on postback.

protected void Page_Load(object sender, EventArgs e)
{
    PopulateDropDownList();
}

will cause it to be reset every time. Instead try:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        PopulateDropDownList();
    }
}
CptSupermrkt
  • 6,844
  • 12
  • 56
  • 87
  • Weird I've done what yo advised but it still doesn't keep the selection. – user310291 Oct 06 '12 at 11:44
  • Hmm, between the two answers here, I can't think of anything else. Almost every time I think it must be something else, it's always a case of re-populating the dropdown list or clearing it accidentally somewhere. You can try editing your question above with some code if you're still having trouble. – CptSupermrkt Oct 09 '12 at 00:11
5

This is very old question, but still I want to answer for others who might be referring this page :

When you have non-unique string in value of drop-down, you will always point to the first item of same value.

For example :

Text = "xyz" Value="0"

Text = "xyz1" Value="0"

Text = "xyz2" Value="0"

Text = "abc" Value="1"

when you select xyz or xyz1 or xyz2, after postback, it goes back to first item which has text as xyz. If you keep unique values, you will not face this issue. I wasted my time and finally got it resolved with this trick.

GMaster9
  • 197
  • 1
  • 6
  • Even older still, just wanted to point out that this was my problem. Each value must be unique. Personally, I think that's stupid. – Bill Norman Apr 06 '18 at 14:35
3
  1. Ensure the Enable.ViewState property is set to true.

  2. And as suggested by cptSup... Make sure that that you are not populating/binding dropdown on page with IsPostback check

Raab
  • 34,778
  • 4
  • 50
  • 65
2

Also make sure you are not checking the DropDownList.SelectedValue in the System.Web.UI.Page.Init method. Due to the ASP.NET page life cycle the SelectedValue won't be available till the System.Web.UI.Page.Load method. At least this was my experience, just now in ASP.NET 4.0.

Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
1

Just adding to GMaster9's answer, in my case I had to put the text = value. Simply making the values unique e.g. 1, 2, 3 ... did not help. Thus :

Text = "xyz" Value="xyz"

Text = "xyz1" Value="xyz1"

Text = "xyz2" Value="xyz2"

Eddie
  • 31
  • 4