C# 如何在asp:checkboxlist中获取选定的项目数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10460378/
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:58:15  来源:igfitidea点击:

how to get selected items count in asp:checkboxlist

c#asp.netvisual-studio

提问by ranjenanil

i have a checkboxlist control

我有一个复选框列表控件

<asp:CheckBoxList ID="chkselectedItems" Font-Size="12px" runat="server"> 
 </asp:CheckBoxList>

and i created listitems on it dynamically.If i checked more than one item from the checkbox list, How i get the selected item count using asp.net

并且我在其上动态创建了列表项。如果我从复选框列表中检查了多个项目,我如何使用 asp.net 获取所选项目数

thanks

谢谢

采纳答案by Pranay Rana

Edit

编辑

int numSelected = 0;
foreach (ListItem li in chkselectedItems.Items)
{
if (li.Selected)
{
numSelected = numSelected + 1;
}
}
Response.Write("Total Number Of CheckBoxes Selected:");
Response.Write(numSelected);

pre

public string[] CheckboxListSelections(System.Web.UI.WebControls.CheckBoxList list)
{
 ArrayList values = new ArrayList();
 for(int counter = 0; counter < list.Items.Count; counter++)
 {
  if(list.Items[counter].Selected)
  {
   values.Add(list.Items[counter].Value);
  }    
 }
 return (String[]) values.ToArray( typeof( string ) );
}

回答by Adil

We will iterate through the checkboxlist and use a counter variable for counting selected items. For every item in checkboxlist we will add 1 to counter variable selCount if item is checked

我们将遍历复选框列表并使用计数器变量来计算所选项目。对于复选框列表中的每个项目,如果项目被选中,我们将向计数器变量 selCount 添加 1

int selCount = 0;   

for(int i= 0; i< chklst.Items.Count; i++) 
  if(chklst.Items[i].Selected)
      selCount++;

// Now selCount will contain the count of selected items

// 现在 selCount 将包含所选项目的计数

回答by Maciej

Use this single line of code:

使用这一行代码:

int selectedCount = chkselectedItems.Items.Cast<ListItem>().Count(li => li.Selected);

回答by ammu

Using Linq

使用 Linq

 var count=  chkmenuitemdef.Items.Cast<ListItem>().Where(c => c.Selected).Count();