[转贴]巧解 有一个无效 SelectedValue,因为它不在项目列表中。异常

最近在做用asp.net 2.0 开发,在将绑定数据到DropDownList。时抛出了一个很奇怪的异常。
异常详细信息: System.ArgumentOutOfRangeException: “DropDownList1”有一个无效 SelectedValue,因为它不在项目列表中。

于是查了一下MSDN:DropDownList.SelectedValue 属性:
此属性返回选定的 ListItem 的 Value 属性。通常使用 SelectedValue 属性确定列表控件中选定项的值。如果选定了多个项,则返回索引最小的选定项的值。如果未选定任何项,则返回一个空字符串 ("")。
SelectedValue 属性还可以用于选择列表控件中的某一项,方法是用该项的值设置此属性。如果列表控件中的任何项都不包含指定值,则会引发 System.ArgumentOutOfRangeException。

检查了一下代码。发现自己在没有绑DropDownList1之前就给DropDownList1.SelectedValue ="qqcrazyer";
怪不得出现异常;这里的DropDownList1没有qqcrazyer这一项。
但是这样赋值在做如市、县连动的值改时候很难避免不碰到赋一个列表没有的值,
怎么办呢?

于是又去反射查了一下SelectedValue的实现,找到了解法。


 1[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Themeable(false), WebSysDescription("ListControl_SelectedValue"), WebCategory("Behavior"), DefaultValue(""), Bindable(true, BindingDirection.TwoWay)]
 2public virtual string SelectedValue
 3{
 4      get
 5      {
 6            int num1 = this.SelectedIndex;
 7            if (num1 >= 0)
 8            {
 9                  return this.Items[num1].Value;
10            }

11            return string.Empty;
12      }

13      set
14      {
15            if (this.Items.Count != 0)
16            {
17                  if ((value == null|| (base.DesignMode && (value.Length == 0)))
18                  {
19                        this.ClearSelection();
20                        return;
21                  }

22                  ListItem item1 = this.Items.FindByValue(value);
23                  if ((((this.Page != null&& this.Page.IsPostBack) && this._stateLoaded) && (item1 == null))
24                  {
25                        throw new ArgumentOutOfRangeException("value", SR.GetString("ListControl_SelectionOutOfRange"new object[] this.ID, "SelectedValue" }));
26                  }

27                  if (item1 != null)
28                  {
29                        this.ClearSelection();
30                        item1.Selected = true;
31                  }

32            }

33            this.cachedSelectedValue = value;
34      }

35}

36 
37


哈哈 原来只有在this.Page.IsPostBack的情况下,赋值才会出错。
只需这样赋值:
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("qqcrazyer"));
就是如果通过FindByValue没有找到指定项则为null,而Items.IndexOf(null)会返回-1.

引自:http://www.cnblogs.com/qqcrazyer/archive/2007/01/26/631455.html

posted @ 2011-11-25 10:12  飞云慕月  阅读(168)  评论(0)    收藏  举报