Question clear ComboBoxes with same numbers

Mano1997

New member
Joined
Aug 12, 2013
Messages
2
Programming Experience
Beginner
Hi, I'am new to vb.net and new to using combo boxes. What i want to do is set up a program where you have 6 combo boxes. Each one has a number 1-6 on it. I wont to make it so if the same number is selected more then once, to display a message saying "You cannot select the same preference more then once" and to clear the boxes with the same numbers. I don't really know what code to us since i haven't used combo boxes before. I've done some research but cant really find anything related to what i am trying to do. Please Help someone. Thank you :)
 
i can send to you codes related to comboBox and i think you can do it alone (because i didn't understand what you want exactly)
 
Hi,

The way to do this is to iterate through all the ComboBox's on your Form each time the SelectedIndexChanged event is fired on any one of your ComboBox's. If a ComboBox is then found with the same value then you can display your message and reset the value of the current ComboBox.

Now, since you have 6 ComboBox's, you need to write the code to do the above once only and then use the Handles Clause of the Event Handler to make each ComboBox use this same Event each time the SelectIndexChanged event fires on any of the ComboBox's. The ComboBox that actually fired the event can then be identified through the sender object.

Here is a quick example using LINQ to do this but this can be easily done with a For Loop, using the same principles demonstrated, if you find that easier:-

VB.NET:
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged, ComboBox6.SelectedIndexChanged, ComboBox5.SelectedIndexChanged, _
                                                                                                   ComboBox4.SelectedIndexChanged, ComboBox3.SelectedIndexChanged, ComboBox2.SelectedIndexChanged
  Dim currentCBChanged As ComboBox = DirectCast(sender, ComboBox)
 
  If Not currentCBChanged.Text = String.Empty Then
    Dim cbValueExists As ComboBox = Me.Controls.OfType(Of ComboBox).Where(Function(ComboBox_X) Not ComboBox_X Is currentCBChanged AndAlso Not ComboBox_X.Text = String.Empty AndAlso ComboBox_X.Text = currentCBChanged.Text).FirstOrDefault
    If Not IsNothing(cbValueExists) Then
      MsgBox(String.Format("Value Already Exists in the ComboBox Named: {0}", cbValueExists.Name))
      currentCBChanged.SelectedIndex = -1
    End If
  End If
End Sub

Hope that helps.

Cheers,

Ian
 
Back
Top