the selected values in my checkboxlist are not adding correctly - ASP.NET

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cluce
    New Member
    • Sep 2007
    • 29

    the selected values in my checkboxlist are not adding correctly - ASP.NET

    I am trying to add only my selected values but its only adding the first selected value in my list repeatedly to the amount of selected items. can someone help me with this?

    for example, lets say I check off 2 in my list. than I check off three other boxes are inline after 2's box in my list not before. no matter what value is in those boxes I still get 8. 2+2+2+2


    Code:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            lblAnswer.Text = ""
            ListBox1.Items.Clear()
            ''add up prices from list 
            Dim total As Decimal
            Dim i As Int32
    
            For i = 0 To CheckBoxList1.Items.Count - 1
                If CheckBoxList1.Items(i).Selected Then
                    total += Decimal.Parse(CDec(CheckBoxList1.SelectedValue.ToString))
                    ListBox1.Items.Add(CheckBoxList1.SelectedValue)
                End If
    
            Next
            lblAnswer.Text = total
    
        End Sub
    End Class
    Last edited by jhardman; Mar 17 '08, 02:50 PM. Reason: moved to the .NET forum, ASP forum is for "classic" ASP
  • DrBunchman
    Recognized Expert Contributor
    • Jan 2008
    • 979

    #2
    Hi cluce,

    Just so as you know - you've posted your question in a classic ASP forum. You'll get better advice if you post any future ASP.NET questions in the .NET forum. Having said that the solution to your problem is as follows:

    You need to replace the two lines inside your For..Next loop which say this:
    Code:
     
    total += Decimal.Parse(CDec(CheckBoxList1.SelectedValue.ToString))
    ListBox1.Items.Add(CheckBoxList1.SelectedValue)
    To this:
    Code:
    total += Decimal.Parse(CDec(CheckBoxList1.Items(i).Value.ToString))
    ListBox1.Items.Add(CheckBoxList1.Items(i).Value.ToString
    The problem was that you weren't selecting a specific checkbox item (using the value of your loop counter, i) to take the value of.

    Without specifiying which item in the CheckBoxList collection to use you were using the value of the first one it found which was checked.

    I hope this helps,

    Dr B

    Comment

    Working...