Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a form containing fourteen controls: Five label controls, three combo boxes, Two text boxes, Two check boxes in button configuration(appearance), and lastly two command buttons.

We all know when we drop a control object on the form if we double click on that object it lets you code an event for that control. For example I double clicked on one of my check box controls and it opens up this event:
VB
Private Sub chkTrusted_CheckedChanged(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles chkTrusted.CheckedChanged

    'Is Button chkTrusted selected?
    If chkTrusted.Checked = True Then
        'Set cboDB.DataSource property to nothing
        cboDB.DataSource = Nothing
        'Clear Combobox items
        cboDB.Items.Clear()
        strCnn = svrCnn.TrustedConnection(cboSvrName.Text, "Master")
        'Get list of databases for this server
        Me.cboDB.DataSource = objDBs.SQLServerCatalogs(strCnn)
        Me.cboTbls.DataSource = objDBs.SQLServerCatalogTables(strCnn)
        'Set button chkStandard to false
        chkStandard.Checked = False
        'Check and see if the User and Password textboxes are enabled
        If (txtUser.Enabled = True) Or (txtPW.Enabled = True) Then
            'Disable User and Password textboxes and clear any contents.
            txtUser.Enabled = False
            txtPW.Enabled = False
            txtUser.Clear()
            txtPW.Clear()
        End If
            'Check and see if Log-In button is enabled
            If btnLogIn.Enabled = True Then
                'Disable button. We are getting data locally
                btnLogIn.Enabled = False
            End If
    End If
End Sub

We placed all these objects on the form during design time. Therefore we can reference them to perform logical operations.

This is want I want to do: I want to dynamically place these fourteen controls on the form during runtime, but if I try to make an AddHandler for the event listed above I will generate a compiler error. This is easy enough to understand, because the objects I'm referencing do not yet exist on the form.

So the question is: How do we make an AddHandler which uses dynamically placed objects inside itself?

Thanks in advance,
MRM256
Posted

You can directly add event handlers to dynamic controls.
Button item = new Button()
item.Click += new EventHandler(btnClick);

void btnClick(object sender, EventArgs e)
{
//Stuff here
}
 
Share this answer
 
VB
Class Form1
 Class MyObject
  Public Event Ran()

  Public sub Run()
   Raise Event Ran()
  End Sub
 End Class

 Private MyList as new List(of MyObject)

 Sub BTN_AddObject_Clicked(BlahBlahBlah as Blah)Handles something on your form that was declared as WTIHEVENTS


  dim x as new MyObject
  MyList.Add(x)
  'Now there's a ref
  addhandler x.Ran addressof AMyClassRan
 End Sub

 Sub AMyClassRan()
   RaiseEvent(Me.Happy)
 End Sub


End Class


I love events.. Can I see your code? Maybe I can be more helpful.
 
Share this answer
 
Comments
MRM256 1-Nov-13 9:21am    
Mr.TMG,

The code inside my original question would be inside an AddHandler routine.

The objects; chkTrusted, cboDB, strCnn, svrCnn, cboTbls, chkStandard, txtUser, txtPW, and btnLogIn are DYNAMICALLY created objects on the form.

The question is: How can I write an AddHandler to use these objects when the compiler can not see them because they are generated at runtime?

I don't think I can clarify it any further,
MRM256
Mr.TMG 2-Nov-13 12:43pm    
I was hoping to see how your controls where being added and if they had anything that could uniquely identify them if there are a variable amount of controls to add.
Are you adding a set number of controls to your form? If so, declare that control as withEvents to keep a permanent reference to it as shown in the second pert of the solution that i just added.
If it's a variable number of controls, then you'l want to use the first example.
MRM256 2-Nov-13 15:25pm    
I have a little demo project I wrote to test out the theory. I'll be glad to send it to you. Maybe it will give you a better insight into my madness :-). I'll need an email address to send it though.

MRM256
Mr.TMG 2-Nov-13 23:39pm    
You can drag and drop into this SkyDrive Folder https://skydrive.live.com/redir?resid=1A24B4A8C01B42BB!1247
Please zip the file first though. I don't check it often so please let me know when you've uploaded it.
MRM256 3-Nov-13 7:58am    
I tried to drop my demo onto your skydive account. I got a message saying I didn't have permission to add file to your account.

What now?
I hope this helps you.

VB
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Setting up a button that will only be on the form
        Dim x As New Button
        'add the button to the form
        Me.Controls.Add(x)
        'add a handler for it
        AddHandler x.Click, AddressOf aButtonWasClicked
        'show some text on the button
        x.Text = "Click ME!!"
    End Sub

    Sub aButtonWasClicked(Sender As Object, e As EventArgs)
        'need to know which button we are working with.
        'to do that declare a variable as button and set it = to the sender object
        Dim x As Button = Sender
        'not you have button properties available to work with
        MessageBox.Show(x.Text & ": Was Clicked!!")
    End Sub

End Class


Please note that if you remove the button then you should also remove the handler so that garbage collector can do it's job.


Another solution:
VB
''' <summary>
    ''' A button obaject declared with events
    ''' </summary>
    ''' <remarks></remarks>
    Private WithEvents MyButton As Button


    Private Sub MyButton_Click(sender As Object, e As EventArgs) Handles MyButton.Click
        MessageBox.Show("MyButton was Clicked.")
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        MyButton = New Button()
        MyButton.Text = "Button"
        Me.Controls.Add(MyButton)
        'Now if you want to remove the control or change it to something else, see RemoveMyButton
    End Sub


    Private Sub RemoveMyButton()
        Me.Controls.Remove(MyButton)

    End Sub
 
Share this answer
 
v3
Based on the project you sent me i think i know what you are doing.
Hopefully you have no problem interpreting this.
What you are trying to do is add controls to your form and handle the evnts without knowing what they are.

the fallowing shows by your code, how to identify the object and declare the correct addhandler for each new control.
You will need to make a sub routine for each type of event and assign handlers accordingly.

there are comments throughout the code attempting to explain whats happening.


VB
Sub add_the_Controls(dtCtrlPlacement As DataTable)
      Dim ctrl As Object
      For I = 0 To dtCtrlPlacement.Rows.Count - 1
          ctrl = objCtrls.cfgCtrls(dtCtrlPlacement.Rows(I), _
                                   cnnAccessCtrlDB)

          ' you should be more specific with this
          'get the type of control so that you can add the appropriate event to handle

          If ctrl.GetType() Is GetType(Windows.Forms.Button) Then
              Dim x As Button = ctrl
              AddHandler x.Click, AddressOf event_btnobject_Clicked
              AddHandler x.MouseHover, AddressOf event_btnobject_hovered

              Me.Controls.Add(x)
          ElseIf ctrl.GetType() Is GetType(Windows.Forms.Label) Then
              Dim x As Label = ctrl
              AddHandler x.Click, AddressOf event_lblobject_Clicked
              Me.Controls.Add(x)
          End If
      Next
  End Sub


  Sub event_btnobject_Clicked(sender As Button, e As EventArgs)
      'Now do whatever you want with the object
  End Sub

  Sub event_btnobject_hovered(sender As Button, e As EventArgs)
      'Now do whatever you want with the object
  End Sub


  Sub event_lblobject_Clicked(sender As Label, e As EventArgs)
      'Now do whatever you want with the object
  End Sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900