有一个无效 SelectedValue,因为它不在项目列表中

“Drp_XX”有一个无效 SelectedValue,因为它不在项目列表中

出现以上异常的原因肯定是将DrowDownList控件的SelectedValue属性赋值为一个列表中不存在的值。那么我们先来了解一下DropDownList的父类ListControl,并针对ListControl.SelectedValue来研究一下。

定义:

获取列表控件中选定项的值,或选择列表控件中包含指定值的项。

异常:

ArgumentOutOfRangeException,选定值是不在可用值列表中,视图状态或其他状态已加载(已执行回发)。 

备注:

当选定的值不在可用值列表中并且执行了回发时,将引发 ArgumentOutOfRangeException 异常。

其中的备注,已经解释了异常出现的原因,并且提供了解决问题的方案:

if (Drp_XX.Items.FindByValue("Your value") != null)
    Drp_XX.SelectedValue = "Your value";
 1 public virtual string SelectedValue
 2 {
 3     get
 4     {
 5         int selectedIndex = this.SelectedIndex;
 6         if (selectedIndex >= 0)
 7         {
 8             return this.Items[selectedIndex].Value;
 9         }
10         return string.Empty;
11     }
12     set
13     {
14         if (this.Items.Count != 0)
15         {
16             if ((value == null) || (base.DesignMode && (value.Length == 0)))
17             {
18                 this.ClearSelection();
19                 return;
20             }
21             ListItem item = this.Items.FindByValue(value);
22             if ((((this.Page != null) && this.Page.IsPostBack) && this._stateLoaded) && (item == null))
23             {
24                 throw new ArgumentOutOfRangeException("value", SR.GetString("ListControl_SelectionOutOfRange", new object[] { this.ID, "SelectedValue" }));
25             }
26             if (item != null)
27             {
28                 this.ClearSelection();
29                 item.Selected = true;
30             }
31         }
32         this.cachedSelectedValue = value;
33     }
34 }
了解更多
原文地址:https://www.cnblogs.com/ccweb/p/3421838.html