Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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

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.

Thanks in advance. :)

like image 524
Dukhabandhu Sahoo Avatar asked May 04 '12 07:05

Dukhabandhu Sahoo


2 Answers

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);
like image 70
Daniel Berg Avatar answered Oct 29 '22 03:10

Daniel Berg


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

like image 28
Milan Svitlica Avatar answered Oct 29 '22 05:10

Milan Svitlica