Analytics


Google

Wednesday, April 23, 2008

User Controls - ASP and Windows Application

User Controls is a wonderful way to reduce repetitive code. Take for example if you have an application that requires multiple approvers. What do you need for each approver section?

Typically, you will need:
  1. Approver Name
  2. Approver ID
  3. Approve Button
  4. Reject Button
  5. Reason for Rejecting
  6. Status (when in display mode)
You could add six controls into your application (either web or windows application) or declare one user control and then add an instance of the user control for each approver.

As for the approve and reject button, the user control can then raiseEvent to the parent page to process the event.

To declare an event in the user control, we need to declare the event and then raise the event when the button is clicked. E.g.

Public Event Approve

Private Sub appSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles appSubmit.Click
RaiseEvent Approve()
End Sub


Another potential use is a lucky draw display panel, where you may want to display multiple info such as:
  1. Employee ID
  2. Employee Name
  3. Dept
Other uses may in cases where multiple screen share the same information such as page header, login account information (I realize this can also be achieved through MasterPage which is introduced in Framework 2.0 and is only available for Web application).

So in the UserControl, we group multiple controls together. We then expose these controls through property so that we can set the values. In some cases, you can add logic such as
  • in the case of approval, do not allow the reject to be clicked unless the reject reason is filled.
  • hide the textbox for login and password and only display the label displaying the username after the person has already logged in. Also add the login logic within the user control so that we do not have to place logic in multiple pages or applications. (to do that we need to compile the code behind as a separate assembly).

No comments: