【问题标题】:Adding a new value to the drop down list box向下拉列表框中添加新值
【发布时间】:2011-07-01 11:36:36
【问题描述】:
我有一个下拉列表框,其中一个值为其他值。我想将这些值移到最后。请帮我解决一下这个。我使用的代码如下
ddlAssetsCountryOthersone.DataSource = lstIMAssetsByCountryOthers;
ddlAssetsCountryOthersone.DataTextField = "AssetDescription";
ddlAssetsCountryOthersone.DataValueField = "AssetDescription";
ddlAssetsCountryOthersone.DataBind();
ddlAssetsCountryOthersone.Items.Remove(
ddlAssetsCountryOthersone.Items.FindByValue(
Constants.PhilosophyAndEmphasis.Other.ToString()));
如何将其他人添加回最后的下拉列表中
【问题讨论】:
标签:
c#
.net
asp.net
drop-down-menu
【解决方案1】:
在你的数据绑定之后试试这个:
ddlAssetsCountryOthersone.Items.Add(new ListItem("Others", "Others"));
顺便说一句,如果你使用插入方法,你可以将你想要的项目插入到你想要的位置。例如,下面的代码将“其他”选项添加到第 4 个订单:
ddlAssetsCountryOthersone.Items.Insert(4, new ListItem("Others", "Others"));
【解决方案2】:
你可以试试
ListItem li = new ListItem("text", "value");
yourDropdown.Items.Insert(yourDropdown.Items.Count, li);
如果下拉列表中有 5 个项目,它将返回 5,因为插入索引从 0 开始
【解决方案3】:
如果您的下拉列表是数据绑定的,您将无法在调用 DataBind() 之后将项目添加到您的控件中,如果您在调用 DataBind() 之前添加它们,无论如何它们将被清除。
您可以在数据绑定发生后使用Insert 或Add,并且可以指定要插入的项目的索引。 Insert 用于在特定位置插入,Add 将附加到底部,如您的情况:
//after databind
//example with insert - (-1 as list is zero based)
ddlMyList.Items.Insert(noOfItems-1, "Other");
或
//add
ddlMyList.Items.Add("Other");
【解决方案4】:
或者:
ListItem li = ddlAssetsCountryOthersone.FindByValue(Constants.PhilosophyAndEmphasis.Other.ToString()));
ddlAssetsCountryOthersone.Remove(li);
ddlAssetsCountryOthersone.Add(li);
这应该可行,请测试 - 并按照 JohnIdol 的建议将 Add 替换为 Insert...
【解决方案5】:
在数据绑定时,从正在数据绑定的列表中添加/删除项目比在数据绑定发生后添加/删除项目要容易得多。
我将围绕 lstIMAssetsByCountryOthers 创建一个包装器,将必要的更改放入新的 IEnumberable 并返回该新对象以进行数据绑定。