简体   繁体   中英

How to calculate how many checkboxes are checked in VB.Net

I have 3 asp.net standard checkbox control and 1 textbox. I check 1 and 3 checkboxes. In textbox how to calculate how many checkboxes are checked? If I checked 1 then textbox result is 1. If I check 1,2 the textbox result is 2. If I check all checkboxes then the result is 3

How to do this in vb.net?

Dim count As Integer
count = 0   
If checkbox1.Checked  Then
    count = count + 1
End If
If checkbox2.Checked  Then
    count = count + 1
End If
If checkbox3.Checked  Then
    count = count + 1
End If   
textbox1.Text = count.ToString()

If you want to check for multiple controls use (I am modifying @Nick code) :

Dim count As Integer
count = 0
For Each ctrl As Control In Page.Controls
    If TypeOf ctrl Is CheckBox Then
       If CType(Control, CheckBox).Checked Then
          count=count+1
       End If
    End If
Next
textbox1.Text = count.ToString()

textbox1.Text = IIf(checkbox1.Checked, 1, 0) + IIf(checkbox2.Checked, 1, 0) + IIf(checkbox3.Checked, 1, 0)

I haven't checked this works, but try:

dim count as integer

count = 0

For Each ctrl As Control In Page.Controls

    If TypeOf ctrl Is Checkbox Then

       count=count+1

    End If

Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM