循环检查复选框 ID 以查看是否选中了任何复选框 ID



我有一张选举系统的选票,我需要遍历选票上的所有复选框,看看它们是选中还是未选中。例如,您只能选择(例如)5 个可用框中的 1 个。我被困住了,一辈子都想不通。以下代码是当用户单击提交按钮时运行的函数。

此代码有效并提交我的选票,但不选中选中的复选框数量。

For Each row As Object In candidatesTable.Rows
If row(1) = ballot_ID Then
Dim checkBox_ID = row(0)
Dim CB As New CheckBox()
CB = mainBallotDiv.FindControl(checkBox_ID)
If CB.Checked Then
Dim addVote As Integer = row("votes")
addVote += 1
candidatesAdapter.addVoteToCandidate(addVote, row(0))
Dim section_ID As Integer = row(2)
Dim voter As String = userGnumber
Dim vote As Integer = checkBox_ID
Dim hasVoted As Boolean = True
votesAdapter.InsertVotes(ballot_ID, section_ID, voter, vote, hasVoted)
End If
End If
Next
Response.Redirect("~/voting/voted.aspx")

我添加了一些东西来尝试让它正确运行,但没有运气,我的代码目前如下。

Dim checkedCount As Integer
For Each row As Object In candidatesTable.Rows
If row(1) = ballot_ID Then
Dim checkBox_ID = row(0)
Dim CB As New CheckBox()
CB = mainBallotDiv.FindControl(checkBox_ID)
Dim section_idFromCB As Integer = candidatesAdapter.getsectionIDfromcandidateID(CB.ID)
Dim voteLimit As Integer = sectionsAdapter.votesbysectionid(section_idFromCB)
If CB.Checked Then
checkedCount += 1
Debug.Write(checkedCount)
If checkedCount > voteLimit Then
' error
Response.Write("<script language=""javascript"">alert('You can not select that many check boxes.');</script>")
Response.Redirect(Request.RawUrl)
Else
' pass
For Each Nrow As Object In candidatesTable.Rows
If Nrow(1) = ballot_ID Then
Dim NcheckBox_ID = row(0)
Dim NCB As New CheckBox()
NCB = mainBallotDiv.FindControl(NcheckBox_ID)
If NCB.Checked Then
Dim addVote As Integer = row("votes")
addVote += 1
candidatesAdapter.addVoteToCandidate(addVote, row(0))
Dim section_ID As Integer = row(2)
Dim voter As String = userGnumber
Dim vote As Integer = checkBox_ID
Dim hasVoted As Boolean = True
votesAdapter.InsertVotes(ballot_ID, section_ID, voter, vote, hasVoted)
End If
End If
Next
Response.Redirect("~/voting/voted.aspx")
End If
End If
End If
Next

任何帮助将不胜感激,并提前感谢。

这是我的建议...

您可以将它们放在List(Of CheckBox)然后您可以根据需要随时访问它们以及获得所需的任何财产。

Dim lstChecked As New List(Of CheckBox)
lstChecked = divcontrol.Controls.OfType(Of CheckBox).Where(Function(ch) ch.Checked = True).ToList

lstChecked将是任何将被检查CheckBox......

For Each checkBox In Me.Controls.OfType(Of CheckBox)
' do something
Next

最新更新