向下拉列表框中添加一个新值

4

我有一个下拉列表框,其中一个选项是“其他”。我想把这个选项挪到最后。请帮我处理一下。我现在使用的代码如下:

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

我该如何将其他选项添加回最后的下拉列表中?

1
我敢打赌,如果有人能理解你想要达到的目标! - TheVillageIdiot
5个回答

7
在数据绑定后尝试以下操作:
ddlAssetsCountryOthersone.Items.Add(new ListItem("Others", "Others"));

顺便提一下,如果您使用插入方法,您可以将所需项目插入到所需位置。例如,下面的代码将“其他”选项添加到第4个订单:

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

1

如果下拉列表是数据绑定的,那么在调用 DataBind() 后您将无法向控件添加项目,如果在调用 DataBind() 之前添加它们,它们将被清除。

在数据绑定完成后,您可以使用 InsertAdd,并指定要插入的项的索引。 Insert 用于在特定位置插入,Add 将附加到底部,就像您的情况一样:

//after databind

//example with insert - (-1 as list is zero based)
ddlMyList.Items.Insert(noOfItems-1, "Other");

或者

//add
ddlMyList.Items.Add("Other");

1

你可以尝试这样做

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

如果下拉菜单中有5个项目,则它将返回5,因为插入索引从0开始。

0

或者:

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

那应该可以,麻烦测试一下 - 根据JohnIdol的建议将Add替换为Insert...


0
在数据绑定时,将列表中的项目添加/删除要比数据绑定后添加/删除要容易得多。 我会创建一个包装器,将lstIMAssetsByCountryOthers中的必要更改转换为新的IEnumberable对象,并返回该新对象以进行数据绑定。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接