I have a sub that handles when 14 ComboBoxes have their Index changed. I am able to cast the sender of the event, and obtain properties from there. However, after that, I want to be able to change the properties of the actual sender, rather than the cast one. How would I do this?
Current code:
Private Sub ComboBoxIndexChange(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged, ComboBox2.SelectedIndexChanged [etc]
Dim myComboBox As ComboBox = sender
Select Case myComboBox.Text
Case "Will"
Me.Controls(myComboBox.Name).Text = "555-555-555"
Case "Bob"
Me.Controls(myComboBox.Name).Text = "555-124-1234"
[etc]
End Select
End Sub
End Class
As you can see, I am currently trying to use
Me.Controls(myComboBox.Name).Text
But I get the error: Object reference not set to an instance of an object.
What can I do?
The
senderparameter in an event handler will (typically) contain a reference to the object that raised the event. In the case of theSelectedIndexChangedevent of aComboBoxcontrol, it will be theComboBoxthat had itsSelectedIndexproperty changed. So in your code sample abovemyComboBoxis referring theComboBoxthat raised the event.To clarify: if you select an item in the drop-down list of a
ComboBoxcontrol, so that it raises theSelectedIndexChangedevent, the sender parameter of the event handler will be that sameComboBox, not a copy of it. This is true for all reference types.Had it been a value type raising the event it would have been a completely different story, but that is a very rare case (it it is never the case when it comes to controls on a form).