D Infosystems
D Infosystems

Reputation: 524

How to count the total no. of asp.net checkboxes, checkboxes checked, no. of checkboxes remain unchecked in webform using vb.net?

How to count the total no. of asp.net checkboxes, checkboxes checked, no. of checkboxes remain unchecked in webform using vb.net ?

I m using Visual studio 2008 with vb as a language ..

I my webform i have 10 checkboxes...

i wanna count total no. of checkboxes in webform in textboxes1 total no. of checkboxes checked in webform in textbox2 total no. of checkboxes remain unchecked in webform in textbox3

Upvotes: 0

Views: 3909

Answers (2)

NoAlias
NoAlias

Reputation: 9193

Dim intTotalCheckBoxes as Integer = 0
Dim intCheckBoxesChecked as Integer = 0
Dim intCheckBoxesUnChecked as Integer = 0

For Each chkbox as Checkbox in Page.Controls

If chkbox.Checked Then

   intCheckBoxesChecked += 1

Else

   intCheckBoxesUnChecked += 1

End If

intTotalCheckBoxes += 1

Next

If you have controls on your page that contain checkboxes and need to know how to recursively include those too, please add a comment and I'll edit the code. Otherwise, this should do the trick.

Upvotes: 0

VinayC
VinayC

Reputation: 49185

Here's a sample C# code, you can easily develop VB code from it.

private int mTotal;
private int mChecked;

private void EnumerateCheckBoxes(Control control)
{
   if (control is CheckBox)
   {
     mTotal++;
     mChecked += ((CheckBox)control).Checked ? 1 : 0;
   }
   else if (control.HasControls())
   {
     foreach(var c in control.Controls) 
     {
       EnumerateCheckBoxes(c);
     }
   }
}

protected void Page_Load(Object sender, EventArgs e)
{
   mTotal = 0;
   mChecked = 0;
   EnumerateCheckBoxes(this.Form);
   textbox1.Text = mTotal.ToString();
   textbox2.Text = mChecked.ToString();
   textbox3.Text = (mTotal - mChecked).ToString();
}

Few things to consider:

  1. This code will count radio buttons as well as because it gets inherited from CheckBox. If that is to be avoided then replace if (control is CheckBox) with if (control.GetType() == typeof(CheckBox))
  2. If you wish to consider checkboxes from CheckBoxList then you have to write another condition to see if control is CheckBoxList and then within condition, enumerate items withing checkboxlist. Items count to be added to total count while selected items to be added to checked count.

Upvotes: 1

Related Questions