Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Dynamically adding code to a button

 

I am dynamically adding a new tabpage, and on that page adding a button (and other controls too). My question is, how do I dynamically add code the click event of that button. This is what I have so far..

 

Dim pagenew As New TabPage

Dim b As Button

b = New Button

With pagenew

.Text = "Page " & (Tab.TabPages.Count - 1)

.Name = pagenew.Text

.Controls.Add(b)

End With

 

Tab.TabPages.Add(pagenew)

 

With b

.Location = New System.Drawing.Point(281, 272)

.Text = "Get Picture"

.Name = "btnGet" & pagenew.Text

.Size = New System.Drawing.Size(80, 24)

 

End With

 

pagenew.Controls.Add(b)

End Sub

 

Any help would be great!

Thanks,

Mike

Posted

Use AddHandler:

 

AddHandler b.Click, AddressOf YourButtonClickSub
...
Private Sub YourButtonClickSub(ByVal sender As Object, ByVal e As System.EventArgs)
'-Click code here. Cast sender to Button to inquire w/c particular button was clicked.
End Sub

Posted

If you know what the code behind your event needs to do then you can just add the control to a predefined event handler (see below). Remember that your event must have the same signature as the event you want to use. If you want to create the code dynamically to include the event hander, I do not know how you would do this. I have never read anything on this for VB. Although have seen it in other languages were you basically call the compiler to parse and run a string. If anyone knows if you can do this in VB, please shed some light.

 

 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
			'Get a new RichTextBox
			Dim dynCTL As New RichTextBox()

			'Add new control to the form
			Me.Controls.Add(dynCTL)

			'Add any handlers we will need for the control
			AddHandler dynCTL.Click, AddressOf CardControls_Click
End Sub


Private Sub CardControls_Click(ByVal sender As Object, ByVal e As System.EventArgs)

'Your event code here for the click event
End Sub

Posted

Although have seen it in other languages were you basically call the compiler to parse and run a string. If anyone knows if you can do this in VB, please shed some light.

 

Take a look at the System.CodeDom class.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...