在asp.net 2.0 網站頁面的開發過程中,經常需要把dropdownlist等列表類控件的selectedvalue值設置為一個從數據庫或其他地方讀取出來的值。
最簡單的辦法就是直接進行指定:
dropdownlist1.selectedvalue = "中國";
但有的時候如果dropdownlist1中沒有"中國"這一項的話,賦值就會出現異常:
異常詳細信息: system.argumentoutofrangeexception: “dropdownlist1”有一個無效 selectedvalue,因為它不在項目列表中。
想要實現的目標:如果指定的值不在列表項中,則不設置選中項,而且不要拋出異常。
查看msdn:
selectedvalue 屬性還可以用于選擇列表控件中的某一項,方法是用該項的值設置此屬性。如果列表控件中的任何項都不包含指定值,則會引發 system.argumentoutofrangeexception。
但奇怪的是這樣賦值在大部分情況下都不會出錯,只是偶爾會出錯,通過反射查了一下selectedvalue的實現,找到了原因。
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;
}
}
原來只有在頁面是ispostback的情況下,賦值才會出錯。
另外這樣寫也會出現異常:
dropdownlist1.items.findbyvalue("中國").selected = true;
最后找到了一種方法可以實現上面的要求:
dropdownlist1.selectedindex = dropdownlist1.items.indexof(dropdownlist1.items.findbyvalue("中國"));
就是如果通過findbyvalue沒有找到指定項則為null,而items.indexof(null)會返回-1
新聞熱點
疑難解答