卸下DropDownList的C#按值多个项目 [英] Remove multiple items by value from dropdownlist C#
本文介绍了卸下DropDownList的C#按值多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为DropDownList控件和drpdemo由几个ListItem如下图所示。
设计code:
< ASP:DropDownList的ID =drpdemo=服务器>
< ASP:ListItem的值=213>选择< / ASP:ListItem的>
&所述; asp的:列表项值=0> 0℃; / ASP:列表项>
&所述; asp的:列表项值=2→2&下; / ASP:列表项>
&所述; asp的:列表项值=3→3&下; / ASP:列表项>
&所述; asp的:列表项值=4→4&下; / ASP:列表项>
< ASP:ListItem的值=5> 5℃/ ASP:ListItem的>
&所述; asp的:列表项值=0> 0℃; / ASP:列表项>
< / ASP:DropDownList的>
在线code:
保护无效的Page_Load(对象发件人,EventArgs的发送)
{
drpdemo.Items.Remove(drpdemo.Items.FindByValue(0));
}
电流输出:
选择
2
3
4
五
0
以上输出自带0,这是我不希望它的输出。
预期输出:
选择
2
3
4
五
注意:不要想用的任何环
块引用>解决方案您将不得不使用一个循环,因为
删除
需要一个列表项
和FindByValue
只返回列表项
。要获得要删除的项目,我们可以这样做:
VAR toDelete = drpDemo.Items
.Cast<&列表项GT;()
。凡(ⅰ= GT; i.Value ==0);然后,你可以这样做:
的foreach(在toDelete VAR项)
{
drpDemo.Items.Remove(项目);
}或者如果你倾向于功能,这样做:
toDelete.ForEach(I => drpDemo.Items.Remove(I));
和都在同一个:
drpDemo.Items
.Cast<&列表项GT;()
。凡(ⅰ= GT; i.Value ==0)
.ToList()
.ForEach(ⅰ= GT; drpDemo.Items.Remove(ⅰ));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.
解决方案You'll have to use a loop because
Remove
takes oneListItem
andFindByValue
returns only oneListItem
.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));
这篇关于卸下DropDownList的C#按值多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文