NuWin NuWin - 6 months ago 33
Vb.net Question

Add Up All Selected Values of ComboBox

I have many combo boxes in which I want to add up all the selected values and display in a label. I have also created an event handler that monitors if a combo box has been selected in which will change the label constantly if a selection is detected. How do I then add up all the values based on the event handler?

Dim cbCtrl = Panel1.Controls.OfType(Of ComboBox)()
For Each ctrl In cbCtrl
AddHandler ctrl.SelectedIndexChanged, AddressOf ctrlSelectedIndexChanged
Next

Private Sub ctrlSelectedIndexChanged(sender As Object, e As EventArgs)
'MsgBox(CType(sender, ComboBox).Text)
For Each ctrl In Panel1.Controls
If (ctrl.GetType() Is GetType(ComboBox)) Then
For i = 0 To 'LastComboBox ???
i = i + ctrl.SelectedItem
label.Text = i
Next
End If
Next
End Sub

Answer

By the looks of it you are already using a 'for-each' to get all the combo box controles, so you could;

Private Sub ctrlSelectedIndexChanged(sender As Object, e As EventArgs)
  dim total as integer = 0 
  For Each ctrl In Panel1.Controls
    If (ctrl.GetType() Is GetType(ComboBox)) Then
         total += CInt(ctrl.SelectedItem)
    End If
  Next
  label.text = total.tostring
End Sub

But if you're working with numbers, why don't you use a nummericupdown?