Reputation: 13
I'm trying to make the MessageBox pop up whenever the value in the combobox changes, instead, it currently pops up on the load and then when the value changes. Not sure what I'm doing wrong here.
Public Class DropDownBox
Private Sub DropDownBox_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dropSource As New Dictionary(Of String, String)()
dropSource.Add("", "")
dropSource.Add("1", "1")
dropSource.Add("2", "2")
dropSource.Add("3", "3")
dropSource.Add("4", "4")
dropSource.Add("5", "5")
dropSource.Add("6", "6")
dropSource.Add("7", "7")
dropSource.Add("8", "8")
dropSource.Add("9", "9")
dropSource.Add("10", "10")
cbox.DataSource = New BindingSource(dropSource, Nothing)
cbox.DisplayMember = "Value"
cbox.ValueMember = "Key"
cbox.Text = Nothing
End Sub
Private Sub cbox_TextChanged(sender As Object, e As EventArgs) Handles cbox.TextChanged
If cbox.Text IsNot Nothing Then
MsgBox("Are you sure?")
Else
End If
End Sub
End Class
Thank you for your help.
Please let me know if you need any additional information on this subject, I've searched all over and haven't been able to figure this out.
Upvotes: 0
Views: 85
Reputation: 32455
Event Combobox.SelectionChangeCommitted
perfectly fit your requirement without extra workarounds.
The SelectionChangeCommitted event is raised only when the user changes the combo box selection
ComboBox.SelectionChangeCommitted Event
Private Sub cbox_SelectionChangeCommitted(sender As Object, e As EventArgs)
Handles cbox.SelectionChangeCommitted
Dim combobox = DirectCast(sender, ComboBox)
If combobox.Text IsNot Nothing Then
MsgBox("Are you sure?")
End If
End Sub
Upvotes: 3
Reputation: 196
I like Youssef's answer, and use that when I have multiple objects, such as an array of controls, that share the same event handler. The downside is that you don't get to identify the event handler in the object's events in the comboboxes at the top of the editor, nor see the routine identified as the handler in the code.
I like this approach:
Private Sub cbox_TextChanged(sender As Object, e As EventArgs) Handles cbox.TextChanged
If Not Me.IsHandleCreated Then Return
If cbox.Text IsNot Nothing Then
MsgBox("Are you sure?")
Else
End If
End Sub
You can also use cbox.IsHandleCreated
Upvotes: 2
Reputation: 4954
I think the value is changing already on loading form.
Anyway here is my idea
Firstly, Remove the event handler, so this line
Private Sub cbox_TextChanged(sender As Object, e As EventArgs) Handles cbox.TextChanged
should be
Private Sub cbox_TextChanged(sender As Object, e As EventArgs)
Secondly, Add the handler again at the end of the form_load by this line
AddHandler cbox.TextChanged, AddressOf cbox_TextChanged
Upvotes: 1