繁体   English   中英

向下拉列表框中添加新值

[英]Adding a new value to the drop down list box

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

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

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

在您的databind之后尝试一下:

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

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

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

如果下拉列表是数据绑定的,则在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 = new ListItem("text", "value");
    yourDropdown.Items.Insert(yourDropdown.Items.Count, li);

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

要么:

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

应该可以,请进行测试-按照JohnIdol的建议,用Insert替换Add ...

进行数据绑定时,从数据绑定的列表中添加/删除项目要比进行数据绑定后添加/删除项目要容易得多。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM