冲突与下拉列表有一个无效的SelectedValue,因为它不存在于项目列表中

本文关键字:于项目 不存在 项目 列表 因为 有一个 下拉列表 无效 SelectedValue 冲突 | 更新日期: 2023-09-27 17:52:56

我最近在我的网站上遇到了一些特定的下拉列表问题。我使用下面的类来填充一些下拉列表

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已经定义了数据。所以我的问题是,这个方法可能会出什么问题,或者我有办法扭转局面吗?

冲突与下拉列表有一个无效的SelectedValue,因为它不存在于项目列表中

在位置0插入一个listtiitem可能会覆盖位置0的绑定项。如果SelectedValue就是那个被覆盖的项那么你就会得到一个错误告诉你SelectedValue无效

我必须在一个类似的代码中工作,其中我在页面加载中多次更改下拉列表的数据源。诀窍是在设置数据源属性之前将SelectedValue设置为null而不是-1。

我知道这个问题已经有答案了,但是它可能会帮助其他有同样问题的人。

相关文章: