【问题标题】:how to get selected items count in asp:checkboxlist如何在 asp:checkboxlist 中获取所选项目的数量
【发布时间】:2012-05-05 09:08:43
【问题描述】:

我有一个复选框列表控件

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

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

谢谢

【问题讨论】:

标签: c# asp.net visual-studio


【解决方案1】:

使用这行代码:

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

【讨论】:

  • 真的太棒了...非常感谢 :) ;)
【解决方案2】:

编辑

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);

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 ) );
}

【讨论】:

  • 有没有可能得到准确的计数?
  • @pranay..你能发布你以前的答案吗?
【解决方案3】:

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

int selCount = 0;   

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

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

【讨论】:

    【解决方案4】:

    使用 Linq

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2013-08-29
      • 1970-01-01
      相关资源
      最近更新 更多