我最近在我的網站中遇到了一些特定的下拉列表問題。 我用下面的類來填補我的一些dropdownlists的與dropdownlist衝突有一個SelectedValue是無效的,因爲它不存在於項目列表中
public static void LoadDdl(string strDescription, string strValue, DataTable dtSource, DropDownList objDropDownList, bool blnAddSelect)
{
objDropDownList.DataTextField = strDescription;
objDropDownList.DataValueField = strValue;
objDropDownList.DataSource = dtSource;
objDropDownList.DataBind();
if (blnAddSelect)
{
objDropDownList.Items.Insert(0, new ListItem("Select...", "-1"));
objDropDownList.SelectedValue = "-1";
}
}
當我到達的數據綁定引發異常:
'ddlAccountTypes' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: 'ddlAccountTypes' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentOutOfRangeException: 'ddlAccountTypes' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value]
System.Web.UI.WebControls.ListControl.PerformDataBinding(IEnumerable dataSource) +1604222
System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) +107
System.Web.UI.WebControls.ListControl.PerformSelect() +34
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +73
Utilities.WebUtilities.LoadDdl(String strDescription, String strValue, DataTable dtSource, DropDownList objDropDownList, Boolean blnAddSelect) in C:\Users\Victor\Desktop\Clubcard\Src\Utilities\WebUtilities.cs:364
ClubCard.Administration.addClient.LoadDdls() +86
ClubCard.Administration.addClient.Page_Load(Object sender, EventArgs e) +130
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
我認爲方法是正確的,因爲大部分時間它的工作原理正好。但是有一個特定頁面因此無法正常工作。首先想到的是,頁面有一個小故障,當它加載的時候它會輸入兩次(!IsPostback),所以第二次進入時,DropDownList可能已經定義了數據。所以我的問題在於,這種方法會出現什麼問題,或者有什麼方法可以解決這個問題?
問候
確切地說,問題在於這一行代碼。 我一直在試圖把某種條件,防止這種異常發生,如objDropDownList.Items.Clear()之前的過程開始,但沒有做這項工作。 如何確保ddl從頭開始還是防止數據綁定進入數據綁定? – Victor
你應該可以先做一個明確的。然後嘗試在數據綁定之前移動if塊。您可以在DropDownList上定義AppendDataBoundItems = True,它將保留您的初始項目(如果存在)。 – TDDdev
我不知道我的做法是否一樣:http://stackoverflow.com/questions/28592179/why-do-i-see-get-a-dropdownlist-has-a-selectedvalue-which-is-invalid。我嘗試過'DDL ID'ClearSelection()',但它沒有工作:/ – SearchForKnowledge