国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

安全的設置dropDownList等列表類控件的selectedValue值

2024-07-21 02:30:03
字體:
來源:轉載
供稿:網友
  • 本文來源于網頁設計愛好者web開發社區http://www.html.org.cn收集整理,歡迎訪問。
  • 在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

    發表評論 共有條評論
    用戶名: 密碼:
    驗證碼: 匿名發表
    主站蜘蛛池模板: 麻城市| 日土县| 女性| 大厂| 阳谷县| 潜山县| 即墨市| 武清区| 德格县| 碌曲县| 衡阳县| 教育| 巴里| 牟定县| 仁寿县| 神木县| 班戈县| 股票| 昔阳县| 灵川县| 遵化市| 屯门区| 富源县| 弋阳县| 马边| 湖口县| 巴彦淖尔市| 富蕴县| 宁河县| 新建县| 称多县| 万全县| 元氏县| 井陉县| 盐山县| 邵阳县| 安岳县| 木兰县| 同德县| 辛集市| 清苑县|