SelectedValue fails on postback in DropDownList

Viewed 2911

I have recently found a strange behaviour inside of the ASP.NET DropDownList that I hope someone could explain.

Basically the problem I am running into is when databinding prior to postback and then setting the SelectedValue to a value that doesn't exist within the list of dataitems the call simply has no effect. However on postback the same call will fail with a ArgumentOutOfRangeException()

'cmbCountry' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

I'm using the following code.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        cmbCountry.DataSource = GetCountries();
        cmbCountry.DataBind();

        cmbCountry.SelectedValue = ""; //No effect
    }
    else
    {
        cmbCountry.SelectedValue = ""; //ArgumentOutOfRangeException is thrown
    }
}

protected List<Country> GetCountries()
{
    List<Country> result = new List<Country>();

    result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test" });
    result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test1" });
    result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test2" });
    result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test3" });

    return result;
}

public class Country
{
    public Country() { }
    public Guid ID { get; set; }
    public string Description { get; set; }
}

Could someone please clarify the cause of this behaviour for me and advise if there are any workarounds?

2 Answers
Related