在下拉列表框中添加新值

我有一个下拉列表框,其中一个值是其他值。 我想将这些值移到最后。 请帮我解决一下这个。 我使用的代码如下

ddlAssetsCountryOthersone.DataSource = lstIMAssetsByCountryOthers; ddlAssetsCountryOthersone.DataTextField = "AssetDescription"; ddlAssetsCountryOthersone.DataValueField = "AssetDescription"; ddlAssetsCountryOthersone.DataBind(); ddlAssetsCountryOthersone.Items.Remove( ddlAssetsCountryOthersone.Items.FindByValue( Constants.PhilosophyAndEmphasis.Other.ToString())); 

如何将其他人添加回最后一个下拉列表中

在数据绑定后尝试这个:

 ddlAssetsCountryOthersone.Items.Add(new ListItem("Others", "Others")); 

顺便说一下,如果使用Insert方法,则可以将所需的项目插入所需的位置。 例如,下面的代码将Other选项添加到第4个订单:

 ddlAssetsCountryOthersone.Items.Insert(4, new ListItem("Others", "Others")); 

你可以试试

 ListItem li = new ListItem("text", "value"); yourDropdown.Items.Insert(yourDropdown.Items.Count, li); 

如果您在下拉列表中有5个项目,它将返回5,因为插入索引从0开始

如果下拉列表是数据绑定的,那么在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"); 

要么:

 ListItem li = ddlAssetsCountryOthersone.FindByValue(Constants.PhilosophyAndEmphasis.Other.ToString())); ddlAssetsCountryOthersone.Remove(li); ddlAssetsCountryOthersone.Add(li); 

这应该工作,请测试 – 并根据JohnIdol的建议替换Add with Insert …

在数据绑定时,从数据绑定列表添加/删除项目要比在数据绑定发生后添加/删除项目容易得多。

我将创建一个围绕lstIMAssetsByCountryOthers的包装器, lstIMAssetsByCountryOthers新的IEnumberable进行必要的更改并返回该新对象为数据绑定。