DropDownList 在執行 DataBind 動作時,若 Items 集合中不存在繫結的欄位值時會發生 Exception。不過 DropDownList 這種設計方式常會造成困擾,很多時候繫結的欄位值無法預期,而且 DropDownList 控制項在這種狀況釋出的錯誤在頁面程式碼中無法處理。

為了解決這種情形,比較快的方式就是直接改掉 DropDownList,在控制項中處理這種無法繫結的情形才是最終的解決方案。那我們該從何處下手呢?想想通常 DropDownList 控制項做資料繫結的是什麼屬性呢?沒錯,就是 SelectedValue 屬性,那我們就從覆寫 SelectedValue 屬性下手,改寫 SelectedValue 屬性的 Set 動作;當寫入 SelectedValue 屬性時的新值不存在 Items 集合中時,就直接設定其 SelectedIndex = -1。這樣就可以很簡單決解掉 DropDownList 繫結錯誤的問題了。

ASP.NET 魔法學院


DotBlogs Tags: DropDownList ServerControl

Feedback

  • Jacky 2008/9/5 下午 06:06 回覆

    # re: 讓 DropDownList DataBind 不再發生錯誤

    好好,但不知怎用,能不能有個例子。

  • jeff377 2008/9/9 下午 12:23 回覆

    # re: 讓 DropDownList DataBind 不再發生錯誤

    to Jacky :

    1.新增一個「伺服器控制項」專案。
    2.將 TBDropDownList  類別加入該專案中。
    3.編譯此組件。
    4.在工具箱加入此組件的控制項,在工具箱就會出現 TBDropDownList 這個控制項。

  • player 2008/9/26 下午 12:32 回覆

    # re: 讓 DropDownList DataBind 不再發生錯誤

    我把你的TBDropDownList 轉C#

    但有問題?
    在FormView 中使用時
    資料繫結接不上?

    ----------------------
    <%@ Register Assembly="SafeWebUI" Namespace="SafeWebUI" TagPrefix="cc2" %>

    <cc2:dropdownlist id="DropDownList3" runat="server" datasourceid="SqlDataSourceGRADE"
    datatextfield="GRADE" datavaluefield="GRADE" selectedvalue='<%# Bind("GRADE") %>' >
    </cc2:dropdownlist>

    把 cc2:dropdownlist 改回 asp:dropdownlist 又正常了?
    ----------------------
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Text;
    using System.Windows.Forms;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace SafeWebUI
    {

    // <summary>
    /// DropDownList 的摘要描述
    /// </summary>
    public partial class DropDownList : System.Web.UI.WebControls.DropDownList
    {
    public DropDownList()
    {
    //
    // TODO: 在此加入建構函式的程式碼
    //
    }

    /// <summary>
    /// 覆寫 SelectedValue 屬性。
    /// </summary>
    public override string SelectedValue
    {
    get
    {
    return base.SelectedValue;
    }
    set
    {
    ListItem oItem = this.Items.FindByValue(value);
    if ((oItem == null))
    {
    this.SelectedIndex = -1; //當 Items 不存在時
    }
    else
    {
    base.SelectedValue = value;
    }
    }
    }
    }
    }

  • jeff377 2008/10/19 上午 11:13 回覆

    # re: 讓 DropDownList DataBind 不再發生錯誤

    to player :
    你的 DropDownList 應該是有設定 DataSourceID 吧?這部分要再覆寫 PerformDataBinding 方法,處理 SelectedValue 的值。

  • jeff377 2008/10/23 上午 07:07 回覆

    # re: 讓 DropDownList DataBind 不再發生錯誤

    to player :
    你的問題可以參考另一篇文章中有解決方案。

    [ASP.NET 控制項實作 Day22] 讓 DropDownList 不再因項目清單不存在而造成錯誤

     

標題 *
名稱 *
Email (將不會被顯示)
Url
回應
登入後使用進階評論
Please add 1 and 8 and type the answer here: