3

I have one dropdownlist named drpdemo and consist some listitems as shown below

Design Code:

<asp:DropDownList ID="drpdemo" runat="server">
    <asp:ListItem Value="213">Select</asp:ListItem>
    <asp:ListItem Value="0">0</asp:ListItem>
    <asp:ListItem Value="2">2</asp:ListItem>
    <asp:ListItem Value="3">3</asp:ListItem>
    <asp:ListItem Value="4">4</asp:ListItem>
    <asp:ListItem Value="5">5</asp:ListItem>
    <asp:ListItem Value="0">0</asp:ListItem>
</asp:DropDownList>

Inline Code:

protected void Page_Load(object sender, EventArgs e)
{
    drpdemo.Items.Remove(drpdemo.Items.FindByValue("0"));
}

Current Output:

Select
  2
  3
  4
  5
  0

Above output comes with the 0, which i don't want it in output.

Expected Output:

Select
   2
   3
   4
   5

Note: Dont want to use any loop.

Christos
  • 53,228
  • 8
  • 76
  • 108

3 Answers3

5

You'll have to use a loop because Remove takes one ListItem and FindByValue returns only one ListItem.

To get the items to delete, we can do:

var toDelete = drpDemo.Items
               .Cast<ListItem>()
               .Where(i => i.Value == "0");

Then you can do:

foreach (var item in toDelete)
{
    drpDemo.Items.Remove(item);
}

Or if you're functionally inclined, do:

toDelete.ForEach(i => drpDemo.Items.Remove(i));

And all in one:

drpDemo.Items
    .Cast<ListItem>()
    .Where(i => i.Value == "0")
    .ToList()
    .ForEach(i => drpDemo.Items.Remove(i));
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • http://stackoverflow.com/questions/27936466/merge-2-or-more-rows-of-a-column-if-other-column-has-same-values-text-in-sqlserv –  Jan 14 '15 at 06:09
1

If you look carefully to your drop down list, you will notice that there are two items with the same value, 0. So the method FindByValue finds the first and then you remove only this. If you had only one ListItem with value 0, then you wouldn't have seen it.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

Dropdown list does not support any method for removing multiple items at once so you will have to use a loop.

If you're ok with using a loop internally, but simply don't want to write one, you can always use LINQ (though I'll leave it for you to judge if it improves readability vs. using a loop).

drpdemo.Items
       .OfType<ListItem>()
       .Where(li => li.Value == "0")
       .ToList()
       .ForEach(li => drpdemo.Items.Remove(li));
decPL
  • 5,384
  • 1
  • 26
  • 36
  • @canon - I don't believe anything I wrote suggests doing so. If I missed anything, would you kindly point me to it? – decPL Jan 09 '15 at 14:08
  • Getting Error-does not contain a definition for 'Remove' and no extension method 'Remove' accepting a first argument of type 'System.Web.UI.WebControls.DropDownList' could be found (are you missing a using directive or an assembly reference?) –  Jan 09 '15 at 14:10