Escolar Documentos
Profissional Documentos
Cultura Documentos
Paul D. Sheriff
PDSA, Inc.
January 2002
Summary: Describes how to create a Windows Form User Control as well as useful enumerations, error
messages, and verification. You will also learn how to add descriptions to your properties and methods
using attributes.
Objectives
Assumptions
The following should be true for you to get the most out of this document:
Contents
Overview of User Controls
Inherited Properties
Inherited Events
Creating Your Own Controls vs. Using Microsoft Controls
Overview of the Employee Number Control
Description of the Employee Number User Control
Create the User Control
Create the Employee Number Project
Create the User Interface
Create Properties
Create Events
Write Event Procedures for Constituent Controls
Create Methods
Add Some Attributes
Build the Test Project
Test for an Invalid Employee Number
Test for a Valid Employee Number
Summary
About The Author
1|Page
Inherited Properties
There are about 30 properties that you will inherit from the UserControl base class. These properties
include all of the common properties you see on normal controls, such as the accessibility properties,
backcolor, forecolor, anchoring, and docking. You can override these properties if you need to, but you
will probably leave most of them as they are.
Inherited Events
A user control that you create inherits about 40 events from the UserControl base class. These events are
the ones that are most common, such as Load, Resize, and Layout events. Your control will also include
some of the low-level mouse and keyboard events, such as Click, DoubleClick, MouseUp, and
MouseDown.
You may override these inherited events if you need to, but it is best if you override only the inherited
On<EventName> method instead of directly overriding the base event, so that future controls may benefit
from the standards.
2|Page
control might look. The control is made up of a label with the text "Employee Number" and a text box that
can be filled in with an employee number.
3|Page
Classes
You will create a class within your user control called EmpNumEventArgs. This class inherits from
System.EventArgs and can thus be passed as the second argument to an event procedure. You will add
two properties to this new class, Message and ErrorNumber, and you will use this class when you raise
the BadEmployeeNumber event from your user control. The idea is to identify what is wrong with the
data the user entered, assign a description of what is wrong to the Message property and an error number to
the ErrorNumber property, and then send this object as the second parameter to the
BadEmployeeNumber event.
Enumerations
Instead of just arbitrarily assigning some error number to the ErrorNumber property of the
EmpNumEventArgs, it is a good idea to create an enumerated type that has a list of the possible error
numbers that could be generated. You will create an enumerated type named EmpNumErrors. This
enumeration will be created with five values, NoError, NotLongEnough, LetterMissing, DashMissing,
NumberMissing. The following section describes the reasons why the error number format could be
wrong.
4|Page
Figure 2. Create the Employee Number User Control using one Label and one Text Box control.
Table 1. Controls and properties to create and set in building the Employee User Control
Control Type
Label
TextBox
Property
Value
Name
lblEmpNum
Text
Employee Number
Name
txtEmpNum
Text
MaxLength
6
CharacterCasing Upper
Create Properties
You will now build some additional properties that allow you to control the look of this User Control. You
will create the following properties in this control:
EmpID
LastName
FirstName
Salary
ConnectionString
Text
5|Page
You create the first five properties (EmpID, LastName, FirstName, Salary, and ConnectionString)
using private member variables and property statements. The Text property is simply a property statement
wrapped around the Text property of the txtEmpNum text box control. The steps are as follows:
Create the following member variables just after the Public Class EmployeeNumber statement as
shown below.
Add the IMPORTS statement, as this will be needed later in this document.
Imports System.ComponentModel
Public Class EmployeeNumber
Inherits System.Windows.Forms.UserControl
' Employee Properties
Private mintEmpId As Integer
Private mstrLastName As String
Private mstrFirstName As String
Private mdecSalary As Decimal
' Connection String
Private mstrConnectString As String
6|Page
Create the Text property as a wrapper around the txtEmpNum text box control.
Public Overrides Property Text() As String
Get
Return txtEmpNum.Text
End Get
Set(ByVal Value As String)
txtEmpNum.Text = Value
End Set
End Property
Notice that the Text property must use the Overrides attribute because the default Text property on the
UserControl class is used to display a title on the User Control.
Create Events
If the user types in an incorrect employee number format, you will want to raise an event back to the client
application so that you can inform the user of the problem with the format. To raise an event from a
control, you must first declare the event within the User Control. Use the Event declaration followed by the
name of the event.
You will also need to pass in the standard parameters you find on all event proceduressender and e. The
sender parameter is declared as an object data type. The e parameter must be declared as a
System.EventArgs type, or some derived class from the System.EventArgs class. In this case, you will
want to create your own class that inherits from the System.EventArgs class because you want to add an
error number property and a message property. These two properties allow you to fill in additional
information about how the employee number is not in the correct format. Below is the declaration that you
will need to write somewhere near the top of the EmployeeNumber User Control class.
' Create event
Public Event BadEmployeeNumber( _
ByVal Sender As System.Object, _
ByVal e As EmpNumEventArgs)
The EmpNumEventArgs class must be created prior to creating this event declaration. Before you can
create the EmpNumEventArgs class, you first need to create an enumeration of error numbers. The
ErrorNumber property within the EmpNumEventArgs class will be defined as this enumeration type.
Create enumerated list
The enumeration you will now create, named EmpNumErrors, has five values declared in it. The
declaration for this enumeration is as follows:
Public Enum EmpNumErrors
NoError = 0
NotLongEnough = 1
LetterMissing = 2
DashMissing = 3
NumberMissing = 4
End Enum
7|Page
Each of these error numbers will be used to convey to the user of this control what the problem is with the
employee number that was typed in. Of course there will be a corresponding message filled in with more
descriptive information, but having an enumeration allows you to check for a specific error
programmatically, and potentially ignore that error as well. For example, you may choose allow a blank
employee number. If this is the case when the BadEmployeeNumber event is raised, you could check to
see whether the ErrorNumber property contained the NumberMissing value. If so, you might not display
the message to the user.
Create an enumeration class
Now you need to create the class that will be used to hold the error number and the message. This new
class, named EmpNumEventArgs, must first inherit from the System.EventArgs class. You must inherit
from this class so you can pass this derived object to the event procedure as the second parameter. Other
than the INHERITS statement, this class is a fairly straightforward class with just two property
declarations: Message and ErrorNumber. The ErrorNumber property is declared as the type enumerated
type EmpNumErrors.
Public Class EmpNumEventArgs
Inherits System.EventArgs
Private mstrMessage As String
Private mintError As EmpNumErrors
<Description("Message to display for this error")> _
Property Message() As String
Get
Return mstrMessage
End Get
Set(ByVal Value As String)
mstrMessage = Value
End Set
End Property
<Description("Error number")> _
Property ErrorNumber() As EmpNumErrors
Get
Return mintError
End Get
Set(ByVal Value As EmpNumErrors)
mintError = Value
End Set
End Property
End Class
You might notice some strange XML-looking stuff in the above class. These are called attributes, and will
be covered later in this document. Now that you have created this class to use for the
BadEmployeeNumber event procedure, you are ready to write the code that checks for the format of the
employee number.
8|Page
9|Page
The code in this event procedure should be very simple to understand. You just check all of the possible
error conditions regarding the number input by the user. If a part of the employee number is invalid, you
assign an error number to a local variable and an appropriate message to another local variable. At the end
of this procedure, you create a new EmpNumEventArgs object, fill in the ErrorNumber and Message
properties with the values in the local variables, and then raise the BadEmployeeNumber event, passing in
the instance of the User Control and the EmpNumEventArgs object.
Create Methods
An additional check you might wish to perform on an employee number is to see whether it exists within a
table in a database. The following method shows how you might validate the data within an Employees
table, and once you find a valid record, populate the additional properties on this control with other
information about the employee. For example, you might fill in the properties from other columns in the
table: EmployeeId (iEmp_id), LastName (szLast_nm), FirstName (sFirst_nm), and Salary
(cSalary_amt).
Public Function EmployeeIsValid() As Boolean
Dim oCmd As OleDb.OleDbCommand
Dim oDR As OleDb.OleDbDataReader
Dim strSQL As String
strSQL = "SELECT iEmp_id, sEmp_num, szLast_nm, "
strSQL &= "sFirst_nm, cSalary_amt "
strSQL &= "FROM Employees "
10 | P a g e
Of course, this method assumes that you have a table called Employees in a database with the structure, as
follows:
CREATE TABLE Employees
(
iEmp_id int IDENTITY (1, 1) NOT NULL
PRIMARY KEY NONCLUSTERED ,
sEmp_num char(6) NULL ,
szLast_nm varchar(25) NULL ,
sFirst_nm char(15) NULL ,
cSalary_amt money NULL
)
11 | P a g e
These attributes can be read by any tool that will read meta-data about a class. These descriptions can be
handy when you distribute a compiled DLL and you want to convey additional information about your
class and properties. The attributes come from the System.ComponentModel NameSpace, which is why
you must import that NameSpace within the file where you will use attributes.
You can apply attributes to the definition of the User Control class itself. This can give you the option of
setting the event to be the default when you double-click on the control. Below, youll find the attribute
that you should add directly above the definition of the EmployeeNumber class. Be sure to either put it on
the same line as the Public Class definition, or include the underscore character, as these attributes must be
placed on the same line as the class definition.
<DefaultEvent("BadEmployeeNumber")> _
Public Class EmployeeNumber
You can assign attributes to properties of the EmployeeNumber class. For example, you can have the
attributes of properties such as EmpID, LastName, and FirstName appear in the Properties Window by
using the Browsable(True) attribute. You can assign a category to the property by using the
Category("Employee") attribute. You can also put in a description attribute that will show up in the
description window below the property window.
<Category("Employee"), Browsable(True), Description("Employee ID")> _
ReadOnly Property EmpID() As Integer
...
<Category("Employee"), Browsable(True), _
Description("Last Name of Employee. Read Only. _
Only filled in after called to _
EmployeeIsValid method.")> _
ReadOnly Property LastName() As String
...
<Category("Employee"), Browsable(True), _
Description("First Name of Employee. Read Only. _
Only filled in after called to _
EmployeeIsValid method.")> __
ReadOnly Property FirstName() As String
...
12 | P a g e
13 | P a g e
You will need to create a connection string function that builds a valid OLEDB provider string.
Private Function ConnectStringBuild() As String
Dim strConn As String
strConn
strConn
strConn
strConn
= "Provider=sqloledb;"
&= "Data Source=(local);"
&= "Initial Catalog=Employees;"
&= "User ID=sa"
Return strConn
End Function
You will need to create the table in SQL Server and add some valid employee information to the table.
Then you can click on the Save button to test out this functionality.
Summary
In this document, you learned how to create a User Control that you can use and reuse on any Windows
form in any application. To reuse this control in any other project, simply customize the toolbox and point
to the DLL that is created. Passing information back in your own custom EventArgs object is an excellent
way to convey additional information to the user of this control. Adding attributes to your control will give
users better information about how to use your control.
14 | P a g e
Paul has co-authored a book entitled ASP.NET Jumpstart. Visit the PDSA, Inc. Web site for more
information.
15 | P a g e