Remove multiple items by value from dropdown c #
I have one dropdownlist named drpdemo and made up of some lists like below.
Project 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>
Internal code:
protected void Page_Load(object sender, EventArgs e)
{
drpdemo.Items.Remove(drpdemo.Items.FindByValue("0"));
}
Current output:
Select
2
3
4
5
0
The above output goes from 0, which I don't need in the output.
Expected Result:
Select
2
3
4
5
Note. Don't want to use any loop.
You will need to use a loop because it Remove
takes one ListItem
and FindByValue
only returns one ListItem
.
To remove items, we can:
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 are functionally configured, follow these steps:
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));
source to share
Dropdown
list does not support any method for removing multiple elements at the same time, so you will have to use a loop.
If you're fine with using a loop internally, but just don't want to write it, you can always use LINQ (although I'll leave that for you to judge if it improves readability or uses a loop).
drpdemo.Items
.OfType<ListItem>()
.Where(li => li.Value == "0")
.ToList()
.ForEach(li => drpdemo.Items.Remove(li));
source to share