How can I refer to the control while I am inside a control’s method in VB.NET?
For example, I want in a textbox to show a message box with that textbox’s text every time the text changes. The code would be something like:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
msgbox("The text is:"+ Me.text)
' ok the line above wont work i already know that, because "Me" refer to the form,
' not the control textbox1
' how i will refer to the textbox1's text???
' i dont want to use "textbox1.text" is there a way similar like the "Me" is for forms?
' because i want to copy-paste a code like this in a lot of controls and do not want to
' have to change in every copy the name to each control name
End Sub
I hope I made myself clear; my English needs some improvement 😀
No, there’s no keyword that allows you to do that. However, every event raised by a control passes in a
senderparameter that you can use to determine which particular control raised that event.Note that this parameter is always typed as a basic
Object(because it can represent any possible control), so you’ll need to downcast to a more specific control class if you need to access any of the unique members that it exposes. Since you’re handling an event raised by aTextBoxcontrol, you know that thesendermust be of typeTextBox, so you can simply useDirectCastto handle the upcasting. You don’t have to worry that anInvalidCastExceptionwill be thrown.For instance, your above example would become:
That being said, there are a couple of concerning things that jump out at me in your question:
Any time that your approach to solving a problem is “copy-pasting” code, you should stop, take a step back, and try to figure out if there’s any better way to achieve your ultimate goal.
For example, if you need every textbox on your form to react in the same way whenever a particular event is raised, you should consider subclassing the existing
TextBoxcontrol and consolidating all of your code in one place. Remember that you can inherit off of most of the standard controls to add custom functionality. This is often a far better solution than copying and pasting code to multiple places in your project. If you ever need to track down a bug or modify that functionality, you’ll only have to change it one place in your code, rather than several. As a somewhat cheekier benefit, you’ll be able to useMeto refer to that control when you’re editing its subclass.You should always prefer to concatenate (combine) strings using the
&operator in VB.NET, rather than the+sign. Or perhaps even better, theString.ConcatorString.Formatmethods.There is no reason to use
MsgBoxin VB.NET, as opposed toMessageBox.Show. No, this won’t improve performance of your application, but it’s a good practice to get into for .NET languages.