【问题标题】:DataBind on a DropDownList throws exception even though no index is selected即使没有选择索引,DropDownList 上的 DataBind 也会引发异常
【发布时间】:2013-02-18 21:38:02
【问题描述】:

所以我得到了这个错误

{"'drpButton1' has a SelectedValue which is invalid because it does not exist in the list of items.\r\nParameter name: value"}

从我能读到的所有内容来看,这是因为 DropDownList 要么有现有项目,要么有一个选定的索引或值,它不在新的数据绑定项目中。

但问题是我可以保证对象中没有现有项目,并且我也可以自信地说没有选择可能超出范围的索引。

这是 DropDownList 对象在 .databind() 调用之前的样子。

这里是直接在导致所有爆炸的 databind() 调用之后。

我的列表对象包含 7 个项目,特别是它包含数据绑定方法随机决定选择的项目。

但这是我用完全相同的数据填满 8 个下拉列表的关键,它在第一个下拉列表中工作得很好。不知道为什么第二个会爆炸。

编辑:这是执行绑定的代码:

这是一个来自 load 方法的 sn-p。第一个调用成功,第二个调用失败,但它不会一直失败。

       private void LoadShortCodeDropDownData()
        {
            // Initilization junk to get the resultList to use.

   base.LoadListDropDown(drpButton0, (IList)resultList, "DeviceShortCodeIndexID", "DeviceShortCodeName", select);
                MessageTextEnabled(drpButton0);

                base.LoadListDropDown(drpButton1, (IList)resultList, "DeviceShortCodeIndexID", "DeviceShortCodeName", select);
                MessageTextEnabled(drpButton1);
}

    protected void LoadListDropDown(DropDownList dropDown, IList list, string valueField, string textField, string insertItem)
    {
        LoadListDropDown(dropDown, list, valueField, textField);
        //dropDown.Items.Insert(0, new ListItem(insertItem, ""));
    }

protected void LoadListDropDown(DropDownList dropDown, IList list, string valueField, string textField)
        {
            dropDown.DataSource = list;
            dropDown.DataValueField = valueField;
            dropDown.DataTextField = textField;
            dropDown.DataBind();
        }

EDIT2:我认为我在这里遇到的真正问题是数据绑定如何选择要选择的项目?我注意到第一个获取数据绑定的下拉列表随机选择列表中的第一个值,而第二个下拉列表出于某种原因尝试绑定到列表中的最后一个值。

【问题讨论】:

  • 你能发布你的实际代码吗?
  • 你能添加执行.DataBind()的代码吗?
  • 在分配数据源值之前尝试设置dropDown.SelectedValue=null; dropDown.Items.Clear();。检查此以获取更多详细信息 - connect.microsoft.com/VisualStudio/feedback/details/666808/…
  • 回复:您的第二次编辑:这很有趣。 resultList 是什么类型的对象? MessageTextEnabled 是做什么的?这是在第一次加载时发生的还是在回发后发生的?通常,除非您告诉它要选择哪些项目或索引,否则 DropDownList 将显示为“选择”第一个项目。
  • 另外:你确定这些方法在页面加载中只被调用一次吗?您可能会在第一次运行时成功绑定,然后在后续运行中失败。

标签: c# asp.net exception


【解决方案1】:

这是在页面第一次加载时发生的,还是在回发后发生的?因为如果它是回发,那么默认情况下您很可能拥有SelectedIndex == 0

我不能保证这会解决问题,但你可以尝试添加

dropDown.SelectedIndex = -1; 

... 到第二个LoadListDropDown 重载的顶部。

【讨论】:

  • 这可行,但现在它拒绝稍后分配值。没有错误,只是没有分配正确的错误。不知道这是如何解决的,因为从未分配过索引,而是分配过什么。
【解决方案2】:

我之前遇到过这个问题,我认为您不能将同一个列表绑定到多个下拉列表。

【讨论】:

  • 虽然你不能让多个下拉列表共享完全相同的 ListItem 对象,但每次执行 DataBind 都应该创建新的 ListItem 对象。将多个下拉列表绑定到相同的数据应该不是问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
相关资源
最近更新 更多