2017-06-13 80 views
0

我有選舉系統的選票,我需要遍歷選票上的所有複選框,以查看它們是否被選中或未選中。您只能選擇(例如)5個可用框中的1個。我被卡住了,不能爲我的生活弄清楚這一點。下面的代碼是當用戶點擊提交按鈕時運行的函數。通過複選框ID循環查看是否有任何選中

此代碼工作並提交我的選票,但不檢查選中複選框的數量。

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 

任何幫助將不勝感激,並在此先感謝。

+0

Directcast也可能來得心應手。 –

回答

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

你們有什麼問題.... downvoting爲什麼? –

+4

我相信你會被拒絕投票,因爲雖然代碼片段沒問題,但如果沒有解釋代碼片段正在做什麼的解釋,答案並不值得。 –

+0

你在開玩笑吧。對簡單而簡單的英文中的一行錯綜複雜的單行代碼需要做出什麼解釋。 –

1

這裏是我的建議...

您可以根據需要以及得到你需要的任何財產隨時把它們放在一個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 ...

+1

謝謝工作正常 – JayyCodez

相關問題