国产探花免费观看_亚洲丰满少妇自慰呻吟_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

    發表評論 共有條評論
    用戶名: 密碼:
    驗證碼: 匿名發表
    主站蜘蛛池模板: 长春市| 仙桃市| 景德镇市| 米泉市| 东台市| 云安县| 贞丰县| 鲁山县| 房山区| 呼图壁县| 慈溪市| 杨浦区| 固镇县| 江永县| 会同县| 鄂州市| 宜良县| 民权县| 山东| 汤原县| 靖州| 荣成市| 民和| 清镇市| 铁岭县| 尼勒克县| 衡阳市| 玉环县| 中山市| 双流县| 锡林郭勒盟| 鹤岗市| 分宜县| 麻城市| 柳江县| 弋阳县| 天祝| 嘉祥县| 东海县| 普宁市| 凤阳县|