[RESOLVED] [2005] Click event for a set of code created controls
In my project I have a set of controls created automatically
VB Code:
Dim i As Integer
Dim tb As New Textbox
For i = 1 to flatPane.Controls.Count
tb.text = "Hello world"
frmDocument.Controls.Add(tb)
Next
Now I want to make this controls react on Click event but I don't know how to do it. The control has not been created in design mode so I don't know how to create a Sub for this event. How I should write the code?
Can anyone help me?
Thanks a lot.
Re: [2005] Click event for a set of code created controls
You still have to write the method to handle the event at design time. The easiest way is to add a control of the appropriate type at design time and have the IDE create an event handler for the desired event. You then delete the control and the method will be left behind, minus its Handles clause. You can then rename the method if desired. To connect your run-time-created controls' events to that method you use the AddHandler statement. Within the event handler you get a reference to the object that raised the event from the 'sender' argument.
Re: [2005] Click event for a set of code created controls
Ok. It worked, but I want to make any sinle control react in a different manner.
For example I create a variable number of textbox controls
For each one I want to display a different text on click_event.
I was thinking to write a code that use the the index of the clicked item in the control collection.
VB Code:
frmMain.Controls.IndexOf([B]specified control[/B])
How do I tell him which control I have clicked?
Re: [2005] Click event for a set of code created controls
:rolleyes:
Quote:
Originally Posted by jmcilhinney
Within the event handler you get a reference to the object that raised the event from the 'sender' argument.
Re: [2005] Click event for a set of code created controls
Create a Dictionary(Of TextBox, String):
VB Code:
Private messagesByTextBox As New Dictionary(Of TextBox, String)
When you create a TextBox you add an item to that Dictionary with the TextBox as the key and the corresponding message as the value:
VB Code:
Dim tb As New TextBox
Dim message As String = "Hello World"
Me.messagesByTextBox.Add(tb, message)
In your event handler you cast the sender as type TextBox and pass it to the Dictionary to get its corresponding message:
VB Code:
Dim tb As TextBox = DirectCast(sender, TextBox)
Dim message As String = Me.messagesByTextBox(tb)
MessageBox.Show(message)
Re: [2005] Click event for a set of code created controls
Ok I have it.
Thanks a lot!