user310291
user310291

Reputation: 38228

Why asp.net dropdown with autopostback doesn't keep my selected value

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 ?

Upvotes: 1

Views: 17247

Answers (5)

Eddie
Eddie

Reputation: 31

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"

Upvotes: 1

GMaster9
GMaster9

Reputation: 197

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.

Upvotes: 5

Brian Ogden
Brian Ogden

Reputation: 19232

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.

Upvotes: 2

Rab
Rab

Reputation: 35582

  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

Upvotes: 3

CptSupermrkt
CptSupermrkt

Reputation: 7134

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();
    }
}

Upvotes: 10

Related Questions