我最近遇到了一个问题,我的网站上有一些特定的下拉列表。 我使用以下类来填充我的一些下拉列表
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可能已经定义了数据。所以我的问题是,这种方法可能出现什么问题,或者有什么方法可以解决这个问题?
此致
答案 0 :(得分:3)
可能是在位置0插入ListItem会覆盖位置0中的数据绑定项。如果SelectedValue实际上是被覆盖的项目,那么您将收到一条错误,告诉您该SelectedValue无效。
答案 1 :(得分:0)
我不得不处理类似的代码,我在页面加载中多次更改下拉列表的数据源。诀窍是在设置数据源属性之前将SelectedValue设置为 null 而不是-1。
我知道这个问题已经得到了回答,但它可能会帮助那些遇到同样问题的人。