ranjenanil
ranjenanil

Reputation: 308

how to get selected items count in asp:checkboxlist

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

thanks

Upvotes: 11

Views: 42296

Answers (4)

ammu
ammu

Reputation: 258

Using Linq

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

Upvotes: 0

Maciej
Maciej

Reputation: 7961

Use this single line of code:

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

Upvotes: 41

Pranay Rana
Pranay Rana

Reputation: 176896

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

Upvotes: 7

Adil
Adil

Reputation: 148110

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

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

Upvotes: 4

Related Questions