gpt4 book ai didi

c# - SelectedValue 在 DropDownList 中回发时失败

转载 作者:太空狗 更新时间:2023-10-29 21:45:57 25 4
gpt4 key购买 nike

我最近在 ASP.NET DropDownList 中发现了一个奇怪的行为,我希望有人能解释一下。

基本上,我遇到的问题是在回发之前进行数据绑定(bind),然后将 SelectedValue 设置为数据项列表中不存在的值,调用根本没有效果。但是,在回发时,相同的调用将失败并出现 ArgumentOutOfRangeException()

'cmbCountry' 有一个无效的 SelectedValue,因为它不存在于项目列表中。参数名称:值

我正在使用以下代码。

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cmbCountry.DataSource = GetCountries();
cmbCountry.DataBind();

cmbCountry.SelectedValue = ""; //No effect
}
else
{
cmbCountry.SelectedValue = ""; //ArgumentOutOfRangeException is thrown
}
}

protected List<Country> GetCountries()
{
List<Country> result = new List<Country>();

result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test" });
result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test1" });
result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test2" });
result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test3" });

return result;
}

public class Country
{
public Country() { }
public Guid ID { get; set; }
public string Description { get; set; }
}

有人可以为我澄清此行为的原因并建议是否有任何解决方法吗?

最佳答案

我不确定为什么要这样设计,但是 DropDownList 只会在 PostBack 上抛出这个异常...这是来自 ILSpy 的 setter 代码:

public virtual string SelectedValue
{
get { ... }
set
{
if (this.Items.Count != 0)
{
if (value == null || (base.DesignMode && value.Length == 0))
{
this.ClearSelection();
return;
}
ListItem listItem = this.Items.FindByValue(value);


/********** Checks IsPostBack here **********/
bool flag = this.Page != null &&
this.Page.IsPostBack &&
this._stateLoaded;
if (flag && listItem == null)
{
throw new ArgumentOutOfRangeException("value",
SR.GetString("ListControl_SelectionOutOfRange", new object[]
{
this.ID,
"SelectedValue"
}));
}
if (listItem != null)
{
this.ClearSelection();
listItem.Selected = true;
}
}
this.cachedSelectedValue = value;
}
}

您可以通过将 SelectedValue 设置为 null 而不是空字符串来解决此问题。

关于c# - SelectedValue 在 DropDownList 中回发时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com