During the development process of ASP.NET 2.0 website pages, it is often necessary to set the SelectedValue value of list controls such as DropDownList to a value read from the database or other places.
The easiest way is to specify it directly:
DropDownList1.SelectedValue = "China";
But sometimes if there is no "China" item in DropDownList1, an exception will occur in the assignment:
Exception details: System.ArgumentOutOfRangeException: "DropDownList1" has an invalid SelectedValue because it is not in the list of items.
What you want to achieve: If the specified value is not in the list item, do not set the selected item and do not throw an exception.
Check out MSDN:
The SelectedValue property can also be used to select an item in a list control by setting the property with the value of the item. If any item in the list control does not contain the specified value, System.ArgumentOutOfRangeException is thrown.
But the strange thing is that such assignment will not go wrong in most cases, but it will occasionally go wrong. I checked the implementation of SelectedValue through reflection and found the reason.
public virtual string SelectedValue
{
get
{
int num1 = this.SelectedIndex;
if (num1 >= 0)
{
return this.Items[num1].Value;
}
return string.Empty;
}
set
{
if (this.Items.Count != 0)
{
if ((value == null) || (base.DesignMode && (value.Length == 0)))
{
this.ClearSelection();
return;
}
ListItem item1 = this.Items.FindByValue(value);
if ((((this.Page != null) && this.Page.IsPostBack) && this._stateLoaded) && (item1 == null))
{
throw new ArgumentOutOfRangeException("value", SR.GetString("ListControl_SelectionOutOfRange", new object[] { this.ID, "SelectedValue" }));
}
if (item1 != null)
{
this.ClearSelection();
item1.Selected = true;
}
}
this.cachedSelectedValue = value;
}
}
It turns out that assignment errors only occur when the page is IsPostBack.
In addition, an exception will occur if you write like this:
DropDownList1.Items.FindByValue("China").Selected = true;
Finally found a way to achieve the above requirements:
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("China"));
That is, if the specified item is not found through FindByValue, it will be null, and Items.IndexOf(null) will return -1
http://www.cnblogs.com/weizhuangzhi/archive/2006/12/13/591251.html