如何从C#的下拉列表中删除除第一项之外的所有项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10444370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:54:34  来源:igfitidea点击:

How to remove all items except the first item from dropdownlist in C#?

c#asp.net

提问by Dukhabandhu Sahoo

I need to clear drpAddressTypes dropdown values except the first item and bind again that dropdownlist.

我需要清除除第一项之外的 drpAddressTypes 下拉值并再次绑定该下拉列表。

drpAddressTypes.Items.Clear();
var lstAddressTypes = repository.GetAddressTypes(userId);
if (lstAddressTypes != null)
{
  foreach (var item in lstAddressTypes)
   {
     var addressType = new ListItem(item, item);
     drpAddressType.Items.Add(addressType);
   }
}

When I am using drpAddressTypes.Items.Clear();it is clearing all items. How can I clear all items except the first item.

当我使用 drpAddressTypes.Items.Clear(); 它正在清除所有项目。如何清除除第一项之外的所有项。

Thanks in advance. :)

提前致谢。:)

采纳答案by Daniel Berg

You could retrive the firstitem and then clear the list and add the item again.

您可以检索第一个项目,然后清除列表并再次添加该项目。

var firstitem = drpAddressType.Items[0];

drpAddressType.Items.Clear();
drpAddressType.Items.Add(firstitem);

回答by Hans Ke?ing

You can just remember the first item, clear everything and then put that remembered item back.

您可以只记住第一项,清除所有内容,然后将记住的项放回去。

ListItem first = drpAddressTypes.Items[0];
drpAddressTypes.Items.Clear();
drpAddressTypes.Items.Add(first);

回答by Milan Svitlica

Use Items.RemoveRange(1, items.Count-1)..

使用Items.RemoveRange(1, items.Count-1)..

回答by Dave Hogan

Something like?

就像是?

Items.RemoveRange(drpAddressTypes.Items.Skip(1))

回答by Rob

drpAddressTypes.Items.RemoveRange(1, drpAddressTypes.Count - 1)

drpAddressTypes.Items.RemoveRange(1, drpAddressTypes.Count - 1)