C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Building custom user control in .Net - Part I


Posted Date: 11 Nov 2004    Resource Type: Articles    Category: .NET Framework
Author: ManojRajanMember Level: Gold    
Rating: 1 out of 5Points: 10



Introduction

User Controls are the best examples of reusability of interfaces, grouped controls and extended functionality. User Controls are similar to other windows control, which can be directly placed on a form. You can either build a component from the scratch or extend the functionality of the controls, which are already available depending on the functionality you need. In this article we will discuss on various aspects of user controls and will walkthrough a live sample.

Prerequisite

• Basic object oriented concepts
• Understanding of class, methods and properties.
• Inbuilt controls of windows forms

All user controls are inherited from System.Windows.Forms.UserControl, which provides the basic functionalities required by all controls and implements basic methods and properties. In the following example we will see how to create a user control by using Windows control library project template. Visual Studio .Net provides all the basic environment needed to build a user control. In our sample we will build a Textbox control which will accepts only digits.

Open the Visual Studio and create a new project and select Windows Control Library template project. Give the name as Mtext. Also specify the location.

Click here to view image

Click on Ok to create the project :

Click here to view image

By default the user control will be named UserControl1. The design window allows defining the graphical interface required for our control. Change the user controls name property to NumText, which will be our control name. Now right click on the Usercontrol file in the solution explorer and select view code. You can see the Class name renamed to NumText. Also rename the Usercontrol1 file to NumText in the solution explorer.

Now we need a control image, which will be displayed in the toolbox after adding it to the toolbox. To display a toolbox image for our control, we will create an image for the control. Right click on the Mtext in the solution explorer and select add new item. From the dialog box select Bitmap and rename it to NumText.bmp as shown in the figure and click on Open.



In the properties window change the height and width of the bitmap image to 16. Now draw the image you want to display. See fig: -



In order to display the toolbox image along with the component, the image file has to be embedded within the component itself, so that the users need only a single dll file containing the component and other resources. Now to include the image in the compiled component library, right click on the NumText.bmp file in the solution explorer and click on properties. And set the BuildAction Property to Embedded Resource.



Let us start designing the interface required for the component. Add a text box to the design view of the User control and change the name of the text box to txtNumberOnly. Also clear the text property of the text box. That is all needed for the interface. Next we need to define properties, which will control the behavior of our controls.

Even though we are creating a textbox control, which accepts only digits, we may want to use our NumText control to accept text as well. For this we can define a public property by which we will control the behavior of the NumText to accept digits only or to accept all characters. Go to the Code View of the NumText control. Type the following statement just under the “Windows Form Designer generated code”: -

Public Property NumbersOnly () As Boolean

And press enter, you can see a definition as shown in the figure



You can see the Get and Set option for the defined property. The Get option let us define the initial value and retrieve value for the property. And the Set option is for assigning a new value to the property. The user can change this property from the properties window after adding our control to the form, like any other control. Now since the defined property is of type Boolean, the user will see a drop down list from which he can select True or False. This property will control the behavior of our NumText control. Since the default behavior of our control is to accept numbers only. We will initialize the NumbersOnly property to “True” in the Get option as given below. Also we have to write code to set the property when the user changes it in the properties window. We need a class level variable to store the property value. Declare a Boolean variable named mNumbersOnly in the global declaration section of the class. And initialize the variable with value True.



Now let us write the functionality, which restricts the user to enter only digits, when the NumbersOnly property is set to True. Write code in the text box key press event.


Private Sub txtNumberOnly_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles txtNumberOnly.KeyPress

'need not process, if the NumbersOnly property is false
If mNumbersOnly = False Then Exit Sub

'need not process, if the proessed key ia BACKSpace
If Asc(e.KeyChar) = 8 Then Exit Sub

'Ascii vlaues of digits is between 48 and 57
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
'if it is anything else then escape the pressed character
e.Handled = True
End If
End Sub

We have defined the property and method for the component. The next step is to build the component. Right click on the project file and select Build to compile the project and create the component. Your first user control is ready.

Now let us see how to test the component. To test, add a new project from the file menu and name it as TestNumText. In the solution explorer right click on the TestNumText and click on Set as startup project. This will enable the added project to run whenever you run the application. To add the NumText control to the test project, right click on the toolbox and select add/remove items. From the dialog box, browse the dll for the NumText component. This will be in the bin directory under the applications root directory. After adding the component you can see our NumText control in the toolbox with the image we created. Add one instance of NumText control to the form. See the property window, you can see the NumbersOnly property there with the value set to True. Now run the application and try entering characters in the NumText box. IT IS WORKING!!!



You may have noticed that our NumText control is not changing its height and width when you resize the control. This is because we have no resize code for this. To do this, open the code window of the NumText control and add the code given below in the resize event of the Usercontrol. In our control we cannot change the height because our textbox control is not wrap able.


Private Sub NumText_Resize(ByVal sender As Object, ByVal e As _
System.EventArgs) Handles MyBase.Resize

' This procedure let the textbox to change the width when the user
‘ resize the usercontrol
txtNumberOnly.Left = 0
txtNumberOnly.Top = 0
txtNumberOnly.Width = Me.Width
' You cannot change the height of the textbox control
' so restrict the user to increase the height of the usercontrol
' greater than the text box height
Me.Height = txtNumberOnly.Height
End Sub

Try changing the height and width of the user control in the test form. You can see that you can only change the width of the Usercontrol. You may have noticed that we are missing a property, which allows us to get and set the value in the NumText. Let us define a Text Property for that purpose. Add a property procedure Text similar to the NumbersOnly property. Since Text property already exists in the base class, which is overridable, we will create the property as overrides.

‘ This attribute allows as to set and get the value in the NumText
Public Overrides Property Text () As String
Get
‘This will assign the initial value
Text = txtNumberOnly.Text
End Get

Set(ByVal Value As String)
‘ Assign the value when it is changed in the properties window
txtNumberOnly.Text = Value
End Set
End Property

This will solve the problem. Now you can store and retrieve the value in the NumText using the Text property. A major problem rose out of this is we are not validating the data that is assigned to the text property here. That means now it is possible that through code someone can put characters into the NumText even if the NumbersOnly property is set to True. To resolve this we need a method, which will check the validity of the data assigned. Create a function ValidateText that will accept one string argument to check whether it contains any characters. The function will return true if the NumbersOnly property is set to false (No validation required) or if the no characters are found in the input parameter.

‘ This function will return false if the data contains any character
‘ value. Returns true if the NumbersOnly property is false
Private Function ValidateText (ByVal Data As String) As Boolean
Dim Counter As Integer
If mNumbersOnly = False Then Return True: Exit Function
For Counter = 1 To Data.Length
If Asc(Data.Substring(Counter, 1)) <> 8 And _ (Asc(Data.Substring(Counter, 1)) < 48 _
Or Asc(Data.Substring(Counter, _ 1)) > 57) Then
RaiseEvent NumericError(Data.Substring(Counter, 1))
Return False
Exit Function
End If
Next
Return True
End Function

Also modify the Text property procedure as given below

' Assign the text value only if the validatetext function returns true
Public Overrides Property Text() As String
Get
If ValidateText(txtNumberOnly.Text) Then Text = txtNumberOnly.Text
End Get
Set(ByVal Value As String)
If ValidateText(Value) Then txtNumberOnly.Text = Value
End Set
End Property

Now let us see how can we create public methods, which the users of this control can call. We will try it by adding a method to clear the content of the text box.
Put the method in the class definition: -

Public Sub ClearText()
txtNumberOnly.Text = ""
End Sub

Note that the method is defined as public so that users of our control can access it. Once you add this method. Build the Usercontrol once more. Now in the test project add one button and in the click event call the ClearText method as shown

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
NumText1.ClearText()
End Sub

We may also require an event to be raised whenever characters are entered in the NumText with the NumbersOnly attribute set to True. User of our control may be interested in knowing when the user enters a character with the NumbersOnly attribute set to True, so that they can write some code in that event. In the global declaration of the class definition declare one event

Public Event NumericError(ByVal CharPressed As Char)

Note that the event is declared as public, so that the users of our control can use it. We will pass one argument to this event, the character the user pressed when the event is triggered. Also remember to change the Keypress event of text box accordingly.

Private Sub txtNumberOnly_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles _
txtNumberOnly.KeyPress

' Need not process, if the NumbersOnly property is false
If mNumbersOnly = False Then Exit Sub

' Need not process, if the proessed key ia BACKSpace
If Asc(e.KeyChar) = 8 Then Exit Sub

' Ascii vlaues of digits is between 48 and 57
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
' If it is anything else then escape the pressed character
e.Handled = True
‘ Event raised for the error
RaiseEvent NumericError(e.KeyChar)
End If
End Sub



Responses

Author: Siti    18 Nov 2004Member Level: Silver   Points : 0
Its working fine. But its not supporting multiline. Pl do provide the code for it.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: How to upload a file with maximum size (MB)
Previous Resource: Showing Hierarchical Data in C#
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use