简体   繁体   English

asp.net:如何从下拉列表中删除项目?

[英]asp.net: How can I remove an item from a dropdownlist?

I have a dropdownlist, and in some cases need to remove an item (in the code-behind).我有一个下拉列表,在某些情况下需要删除一个项目(在代码隐藏中)。 I need to remove the item based on the value of the item.我需要根据项目的价值删除项目。

How can I do this?我怎样才能做到这一点?

你可以使用这个:

myDropDown.Items.Remove(myDropDown.Items.FindByValue("TextToFind"));

Code:代码:

ListItem removeItem= myDropDown.Items.FindByValue("TextToFind");
drpCategory.Items.Remove(removeItem);

Replace "TextToFind" with the item you want to remove.将“TextToFind”替换为您要删除的项目。

myDropDown.Items.Remove(myDropDown.Items.FindByText("TextToFind"))

You can use the您可以使用

myDropDown.Items.Remove(ListItem li);

or或者

myDropDown.Items.RemoveAt(int index);

to remove it using C#.使用 C# 删除它。

There is also a slightly simpler way of removing the value.还有一种稍微简单的方法可以删除该值。

mydropdownid.Items.Remove("Chicago"); 
<dropdown id=mydropdown .....>

values价值观

  • Florida佛罗里达
  • Texas德克萨斯州
  • Utah犹他州
  • Chicago芝加哥

myDropDown.Items.Remove(myDropDown.Items.FindByText("Chicago"));

I have Done Like this, i have remove all items except the value coming as 1 and 3.我已经这样做了,我已经删除了除 1 和 3 之外的所有项目。

ListItemCollection liCol = ddlcustomertype.Items;
for (int i = 0; i < liCol.Count;i++ )
{
    ListItem li = liCol[i];
    if (li.Value != "1" || li.Value != "3")
        ddlcustomertype.Items.Remove(li);
}

As other people have answered, you need to do;正如其他人所回答的那样,您需要这样做;

myDropDown.Items.Remove(ListItem li);

but if you want the page to refresh asynchronously, the dropdown needs to be inside an asp:UpdatePanel但如果您希望页面异步刷新,则下拉菜单需要在asp:UpdatePanel

after you do the Remove call, you need to call:执行Remove调用后,您需要调用:

yourPanel.Update();

Try this code.试试这个代码。

If you can add any item and set value in dropdown then try it.如果您可以添加任何项目并在下拉列表中设置值,请尝试一下。

 dropdown1.Items.Insert(0, new ListItem("---All---", "0"));

You can Removed Item in dropdown then try it.您可以在下拉列表中删除项目然后尝试。

 ListItem removeItem = dropdown1.Items.FindByText("--Please Select--");
 dropdown1.Items.Remove(removeItem);

I would add an identifying Id or class to the dropbox and remove using Javascript.我会在 Dropbox 中添加一个识别 Id 或类,然后使用 Javascript 删除。

The article here should help. 这里的文章应该会有所帮助。

D D

to insert into DropDownList:插入 DropDownList:

DropDownList.Items.Insert(0, new ListItem("-- Select item --", "0"));

and to remove item from DropDownList:并从 DropDownList 中删除项目:

DropDownList.Items.Remove(new ListItem("-- Select item --", "0"));

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

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