mikef74 Posted July 30, 2003 Posted July 30, 2003 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 Quote
JABE Posted July 30, 2003 Posted July 30, 2003 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 Quote
bfellwock Posted July 30, 2003 Posted July 30, 2003 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 Quote
JABE Posted July 31, 2003 Posted July 31, 2003 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. Quote
*Experts* mutant Posted July 31, 2003 *Experts* Posted July 31, 2003 (edited) Or :), look here: http://www.xtremedotnettalk.com/showthread.php?s=&threadid=72201 Divil wrote a great article on having apllications scriptable. Edited July 31, 2003 by mutant Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.