Vous êtes sur la page 1sur 9

Extending a TextBox Control to add custom Properties VB.

Net 2008
It's been so long that i wanted to write articles about my experience in programming but i never had the courage to do that until now but it comes to my mind that i must do this. it is now or never so here i am, writing my first article. I've been writing programs since 2005 and i still remember one of the problem that i always encounter is the text validation in the text boxes.Normally, Textbox control does not have a property that will filter or validate the texts that are inputted inside it. For example, if you need to have a textbox that will strictly accept only numbers, you will have to put the codes shown below inside its keypress event: VB.Net Code:

Private Sub TBox_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TBox.KeyPress If Not IsNumeric(e.KeyChar) And Asc(e.KeyChar) <> 8 Then e.Handled = True End If
End Sub
or if you need it to accept characters only. you only have to modify some part of the codes shown above. it will turn out like this:

Private Sub TBox_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TBox.KeyPress If IsNumeric(e.KeyChar) Then e.Handled = True End If End Sub
We used the IsNumeric() function to restrict the text that is being inputted in the textbox. This function determines whether the text that is being enteredin the textbox is numeric or not. Also, we include exclude the Backspace in the restriction that is why we have the code 'And Asc(e.KeyChar) <> 8' it is very importantto always remember the Asc equivalent of each characters in the keyboard but for now, we only used Backspace(8) because it must be always excluded from the restriction. Also if we need a certain procedure to run whenever we press the enter key while the cursor is in the Text box, we will have to add this code just before any code in the keypress event of the textbox.

Private Sub TBox_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TBox.KeyPress If Asc(e.KeyChar) = 13 Then 'Call the Procedure Here End If If IsNumeric(e.KeyChar) Then e.Handled = True End If End Sub
There is a lot of method to do this restriction but this is the best way for me to do that.

Anyway, this isn't really the problem that i always encounter.Imagine, if you have a lot of textboxes in your form that are needed to be filtered, you must type or copy and paste the codes to each keypress event?! The solution that i've made before is to create a subprocedure to call in the keypress event of the textbox. Here's the code: Private Sub NumericOnly(ByVal e As KeyPressEventArgs) If Not IsNumeric(e.KeyChar) And Asc(e.KeyChar) <> 8 Then e.Handled = True End If End Sub and i will only have to call the sub procedure in the keypress event like this: Private Sub TBox_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TBox.KeyPress NumericOnly(e) End Sub The good thing with this is that i do not have to type the code again and again in each textbox. all i have to do is call the sub procedure that i've created. but still i am not satisfied with this so i still tried to find a way until i learned things about user controls. User Controls are the controls which are created by the user and they are based on the class System.Windows.Forms.UserControl.Like standard controls, user controls support properties, methods and events. Once a user control is created it can be added toany form or any number of forms like all other controls. So this article is mainly about adding properties in a Text box control in Visual Basic. What we are going to do is inherit the Text box Class and create additional properties to the Text box. The first property that we are going to add is the Text Filter wherein the Text box will only allow text based on the given filter parameter like NumericOnly or CharacterOnly. To create a user control select File->New->Project->Visual Basic Projects and select Windows Control Library from the templates, name it as MyTextBox and click OK. The image below displays the new project dialogue to add a User Control project.

The form that opens after clicking OK looks like the image below. It looks similar to a normal form.

Well, we don't need this form so you can just remove it by right clicking on it in the Solution explorer and select 'delete'

The next thing that we are going to do is add a Class in the project. Right click on the project in the Solution explorer > Add > Class

A dialog box will appear, Name your class as xTextBox and click Ok Now, we are ready to go coding! This is the complete codes of your Class: Public Class xTextBox Inherits TextBox Public Event OnEnterKeyPress() Dim MyInput As Cinput Public Property CharacterInput() As Cinput Get Return Me.MyInput End Get Set(ByVal value As Cinput) Me.MyInput = value

End Set End Property Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs) MyBase.OnKeyPress(e) If Asc(e.KeyChar) = 13 Then RaiseEvent OnEnterKeyPress() End If Select Case Me.MyInput Case Cinput.CharactersOnly If IsNumeric(e.KeyChar) Then e.Handled = True End If Case Cinput.NumericOnly If Not IsNumeric(e.KeyChar) And Asc(e.KeyChar) <> 8 Then e.Handled = True End If End Select End Sub End Class Public Enum Cinput NumericOnly CharactersOnly End Enum Ok, let us discuss what we did in the codes above. Inherits Textbox First we Inherits the Textbox class so that we can use all of its properties and methods. Public EventOnEnterKeyPress() Next, we Declared a new event with the nameOnEnterKeyPress. We will trigger this event each time the user press the Enter key while the cursor is inside the text box. Dim MyInput As Cinput We declare an instance of the Cinput. As you have noticed, we've created an enumeration with the name Cinput. this is to allow the user to select only the items that belongs to the specific enumeration. This done to prevent invalid inputs from the user. For more info or tutorial about Enumeration, you can check out this sitehttp://aspalliance.com/292 Public Property CharacterInput() As Cinput Get Return Me.MyInput End Get Set(ByVal value As Cinput) Me.MyInput = value End Set End Property Next, we've created this property to allow the user to specify what type of Character Input he would like to be filtered. Based on the Enumeration, we only have two types of Input, NumericOnly and CharacterOnly. This is not limited to only two choices. You can add SymbolsOnly or whatever you want but make sure that you will specify the kind of restriction in the keypress event. Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs) MyBase.OnKeyPress(e) End Sub What we did is we overrides the keypress event of the inherited Text box Classso we can add codes in it. this is where we will put the codes that i have discussed atthe beginning of this article. If Asc(e.KeyChar) = 13 Then RaiseEvent OnEnterKeyPress() End If This code simply Raise or Trigger theOnEnterKeyPress event whenever the user press the enter key. Note: the Asc value of Enter key is (13). The next codes are the one that i've discussed a while ago so i don't think i have to do it again so let's continue to the next step.Build the project by pressing ctrl+shift+b or Right click on the project and select Build

Once you are done, It is now time to test our newly created Control. Create a new visual basic project > Windows Form Application and click ok.

In the Toolbox, Right click on the General Tab and select Choose Item.

A dialog box will appear.

Click browse and locate the newly created MyTextBox.dll File Mostly if you are using VS2008, It can be found in >My Documents>Visual Studio 2008>Projects>'Name of the Solution'>'Name of the Project'>Bin>Debug

Click Open and then Ok. You'll notice that a new control with the name xTextBox is added in the General Tab of your Toolbox. This is the control that we have made a while ago.

Now, drag this control to your Form and go to its properties window. You will see that a new property with the name 'CharacterInput' was added to the TextBox control. Show its content and you will see two contents of the enumeration that we have made before.

Leave the CharacterInput to Numeric Only and run the program by pression F5 or clicking the play icon in the tools menu. During runtime, try to enter numbers.The Text box accepted it right? Now, try to type any characters from A-Z, what happened? Amazing... LOL. Now stop the project and set the Character Input to CharactersOnly and run the project again. Basically

it will again restrict the text input based on the given parameter. Stop the program again and double click the TextBox control. The Code behind will show and in the upper right part of it, there is a dropdown containing all the events of the TextBox. Look for an event named: OnKeyEnterPress

Did you found it? indeed, we now have a new Textbox event that you cannot find from a normal Textbox Control. As you remember, this is the event that we have added a while ago in our xTextBox Class. Click this event and Visual Basic will Automatically generate a sub procedure for this event. Now put the codes below inside the OnKeyPress event and run the program again. MessageBox.Show("You Pressed Enter Key", "", MessageBoxButtons.OK, MessageBoxIcon.Information) Make sure that the cursor is inside the Text box and then press Enter. You will see that each time you press the Enter key, the OnKeyPress event is triggered.

We could see that the codes that we add in the class a while ago are working. These are just some of the powerful features of user controls. Try to experiment by adding codes to your xTextBox Class. I'll be posting another properties and events for our xTextBox Class soon but I'm afraid I have to end this article for now. Good Luck and Happy Coding!!