EziData Solutions

Web, NET and SQL Server

Adding Events to Web User Controls in VB.NET

In a previous post, Creating Web Custom Controls in VB.NET we discussed how to create a very simple Web User Control, including how to respond to events raised by the controls contained within the Web User Control. In this post, we are going to extend upon this functionality and disuss how to handle events raised within the Web User Control from the page containing the the control. In otherwords, we want to learn how to tell the containing page when an event within the Web User Control has been raised and carry out some processing based on the results.

Firstly, we will need to make some changes to our Web Custom Web Control, code behind file named CustomDropDown.ascx.vb. To start with, we will declare a public Event called ListChanged.

Public Event ListChanged(ByVal sender As Object, ByVal e As EventArgs)

We then modify the DropDownList SelectedIndexChanged event to raise our new public Event.

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
               Handles DropDownList1.SelectedIndexChanged
         Me.Label1.Text = Me.DropDownList1.SelectedValue
         RaiseEvent ListChanged(sender, e)
End Sub

Now we can make use of the ListChanged Event within the containing page, in this case the default.aspx page. When we dragged the CustomDropDown control onto the design surface of the dafault.aspx page Visual Studio added a few lines of code to the source view. By default, it named our control CustomDropDown1 and registered the control within a Page declaration. Start by adding a label to default.aspx in which we can display a message when the event is raised.

In the code behind page, default.aspx.vb, we can add some code to handle the ListChanged Event.

Private Sub CustomDropDown1_ListChanged(ByVal sender As Object, ByVal e As EventArgs) Handles CustomDropDown1.ListChanged
         Me.Label1.Text = "List Changed"
End Sub

When you build and run the page and select an emplyee, the employees PayrollID is displayed in the label inside the Web User Control as implemented in the previous post, but now we also have a second label that displays the text 'List Changed' after we have selected an employee. This simple example shows how it possible to handle a sinigle event within the Web User Control, in this case the SelectedIndexChanged event, from both inside the control and on the containing page.


In the next post we will expand upon this functionality and learn how to create and handle custom events for Web User Controls.

Posted: Oct 08 2009, 19:13 by Admin | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: VB.NET | VB.NET