I recently discovered a weird behavior inside an ASP.NET DropDownList that I hope someone can explain.
Basically the problem I am facing is data binding before postback, and then setting SelectedValue to a value that does not exist in the data list, that the call simply has no effect. However, upon postback, the same call will end with ArgumentOutOfRangeException()
'cmbCountry' has a SelectedValue value, which is not valid because it does not exist in the list of items. Parameter Name: Value
I am 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; } }
Can someone clarify the reason for this behavior for me and let me know if there are any workarounds?
source share