<a href="http://www.micropoll.com/akira/mpview/585320-168921">Click Here for Poll</a><a href="http://www.questionpro.com" title="online surveys">Online Survey</a><BR> | <a href="http://www.micropoll.com" title="Website Polls">Website Polls</a><BR> | <BR><a href="http://www.micropoll.com/akira/MicroPoll?mode=html&id=168921">View MicroPoll</A></div>

Visual Studio 2010!

Read now >

Windows Mobile Development Thoughts

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Dynamic Code Creation Techniques in VB.NET
By John Mueller

Rate This Article: Add This Article To:

Dynamic Code Creation Techniques in VB.NET - Dynamic Controls
( Page 2 of 4 )

Working with Dynamic Controls

Many developers will need to work with dynamically created controls at some point in their career. The example in this case adds LinkLabels to a FlowLayoutPanel. You might use such a setup to record and save commonly used URLs, files, locations on a network, or any number of other resource locations. The example doesn’t actually save the links, but you could use XML serialization to do so (see the article entitled “XML Serialization: Better than the Registry” at http://www.devsource.com/c/a/Techniques/XML-Serialization-Better-than-the-Registry for details).

Every time a user clicks Test, the example creates a new LinkLabel control dynamically. The actual code for performing this task isn’t complex. Listing 1 shows what you might typically do to create such a control and place it in the FlowLayoutPanel, lstLabels.

Listing 1: Adding New Links to a FlowLayoutPanel

Private Sub btnTest_Click() 
Handles btnTest.Click
    ' Create a link.
    Dim NewLink As LinkLabel = 
        New LinkLabel()

    ' Add some properties to it.
    NewLink.Text = DateTime.Now
        .ToLongTimeString()

    ' Set the click event handler.
    AddHandler NewLink.Click,
        AddressOf NewLink_Click

    ' Place the button on the form.
    lstLinks.Controls.Add(NewLink)

End Sub

As you might expect, the code begins by creating a new LinkLabel and assigning some values to its properties. The example simply uses the current time. Your code would probably provide access to an actual resource. However, the effect is similar to the one shown in Figure 1.

Figure 1: A list of LinkLabels.

Notice that the code also assigns a handler to the link’s Click event. You must use the AddHandler technique shown in this example because the normal Handles keyword route won’t work. For one thing, you don’t know the name of the control when you design the application. Even if you did assign the control a name, you don’t know how many controls the user will create, so there isn’t any way to know how many handlers to create. The handler code will likely be similar to each of the controls, so there’s no point in creating multiple handlers anyway. The handler code for this example appears in Listing 2.

Listing 2: Handling the Dynamic Control Click Event

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

    ' Verify that you actually have a LinkLabel
    If Not sender.GetType() Is GetType(LinkLabel) Then
        MessageBox.Show("Wrong control type provided!")
        Return
    End If

    ' Convert the input sender to a Button.
    Dim ThisLink As LinkLabel = sender

    ' Show that we have the correct button.
    MessageBox.Show("You created this link at: " + ThisLink.Text)
End Sub

You might have noticed that the event handler in Listing 1 uses a relaxed delegate—it doesn’t include the ByVal sender As System.Object and ByVal e As System.EventArgs parameters because it doesn’t need them. However, when you create an event handler for dynamically created controls, you normally do need the ByVal sender As System.Object parameter, which means including both of them.

One error that some developers make when creating an event handler for dynamically created controls is not checking the type of the incoming control. The sender object could contain anything and if your event handler isn’t set up to handle anything, you need to be more selective. The example code begins by checking the type of the incoming control object. This code prevents the sender from doing something like this:

Private Sub btnTest2_Click() Handles btnTest2.Click
    ' Create a link.
    Dim NewButton As Button = New Button()

    ' Add some properties to it.
    NewButton.Text = DateTime.Now.ToLongTimeString()

    ' Set the click event handler.
    AddHandler NewButton.Click, AddressOf NewLink_Click

    ' Place the button on the form.
    lstLinks.Controls.Add(NewButton)

End Sub

This code creates a Button in the FlowLayoutPanel, which works fine, except that the event handler won’t work with a Button as written. If you do plan to service multiple control types, you need to provide unique handling for each control type. You can use multiple event handlers or provide some type of selection criteria in a single event handler.

The NewLink_Click() event handler goes on to convert the incoming sender to a specific type, a LinkLabel in this case. The code can then access LinkLabel properties and interact with it in other ways. In this case, the example merely displays a dialog box that tells you when you created the link.



 
 
>>> More ASP and .Net Coding Techniques Articles          >>> More By John Mueller