extending a textbox control to add custom properties vb.net 2008

Upload: joao-mendes

Post on 03-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    1/9

    Extending a TextBox Control to add custom Properties VB.Net2008

    It's been so long that i wanted to write articles about my experience in programming but inever had the courage to do that until now but it comes to my mind that i must do this. it isnow 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 alwaysencounter is the text validation in the text boxes. Normally, Textbox control does not have aproperty that will filter or validate the texts that are inputted inside it. For example, if youneed to have a textbox that will strictly accept only numbers, you will have to put the codesshown below inside its keypress event:

    VB.Net Code:

    Pr i vat e Sub TBox_KeyPr ess( ByVal sender As Obj ect , ByVal eAs KeyPr essEvent Ar gs)Handl es TBox. KeyPr ess

    I f Not I sNumer i c( e. KeyChar ) And Asc( e. KeyChar ) 8 Thene. Handl ed = Tr ueEnd I f

    End Subor if you need it to accept characters only. you only have to modify some part of the codesshown above. it will turn out like this:

    Pr i vat e Sub TBox_KeyPr ess( ByVal sender As Obj ect , ByVal eAs KeyPr essEvent Ar gs)Handl es TBox. KeyPr ess

    I f I sNumer i c( e. KeyChar ) Thene. Handl ed = Tr ueEnd I f

    End SubWe used the IsNumeric() function to restrict the text that is being inputted in the textbox.This function determines whether the text that is being entered in 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 important to always remember the Asc equivalent of eachcharacters in the keyboard but for now, we only used Backspace(8) because it must be alwaysexcluded from the restriction.

    Also if we need a certain procedure to run whenever we press the enter key while the cursoris in the Text box, we will have to add this code just before any code in the keypress event ofthe textbox.

    Pr i vat e Sub TBox_KeyPr ess( ByVal sender As Obj ect , ByVal eAs KeyPr essEvent Ar gs)Handl es TBox. KeyPr ess

    I f Asc( e. KeyChar) = 13 Then' Cal l t he Procedur e Her eEnd I f

    I f I sNumer i c( e. KeyChar ) Thene. Handl ed = Tr ueEnd I fEnd Sub

    There is a lot of method to do this restriction but this is the best way for me to do that.

    http://spac3crow.webs.com/apps/profile/53795949/
  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    2/9

    Anyway, this isn't really the problem that i always encounter. Imagine, if you have a lot oftextboxes in your form that are needed to be filtered, you must type or copy and paste thecodes to each keypress event?!

    The solution that i've made before is to create a subprocedure to call in the keypress event ofthe textbox. Here's the code:Pr i vate Sub Numeri cOnl y( ByVal e As KeyPressEvent Ar gs)I f Not I sNumeri c( e. KeyChar ) And Asc( e. KeyChar ) 8 Thene. Handl ed = TrueEnd I f

    End Suband i will only have to call the sub procedure in the keypress event like this:

    Pr i vate Sub TBox_KeyPr ess( ByVal sender As Obj ect , ByVal e AsKeyPressEvent Ar gs)Handl es TBox. KeyPressNumer i cOnl y( e)End SubThe good thing with this is that i do not have to type the code again and again in eachtextbox. all i have to do is call thesub procedure that i've created. but still i am not satisfied with this so i still tried to find away until i learned things about

    user controls.User Controls are the controls which are created by the user and they are based on the classSystem.Windows.Forms.UserControl. Like standard controls, user controls support properties,methods and events. Once a user control is created it can be added to any form or anynumber of forms like all other controls.

    So this article is mainly about adding properties in a Text box control in Visual Basic. Whatwe are going to do is inherit the Text box Class and create additional properties to the Textbox.

    The first property that we are going to add is the Text Filter wherein the Text box will onlyallow text based on the given filter parameter like NumericOnly or CharacterOnly.

    To create a user control select File->New->Project->Visual Basic Projects and selectWindows Control Library from the templates, name it as MyTextBox and click OK. The imagebelow 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 normalform.

  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    3/9

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

    The next thing that we are going to do is add a Class in the project. Right click on the projectin 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:

    Publ i c Cl ass xText BoxI nheri t s TextBox

    Publ i c Event OnEnter KeyPress( )Di m MyI nput As Ci nputPubl i c Propert y Charact erI nput ( ) As Ci nputGetRet urn Me. MyI nputEnd GetSet ( ByVal val ue As Ci nput)Me. MyI nput = val ue

  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    4/9

    En SetEnd Proper t yProtect ed Overr i des Sub OnKeyPr ess( ByVal e AsSyst em. Wi ndows. Forms. KeyPressEvent Ar gs)MyBase. OnKeyPr ess( e)I f Asc( e. KeyChar ) = 13 Then

    Rai seEvent OnEnter KeyPress( )End I f

    Sel ect Case Me. MyI nput

    Case Ci nput. Char actersOnl y

    I f I sNumeri c( e. KeyChar) Thene. Handl ed = TrueEnd I f

    Case Ci nput . Numer i cOnl yI f Not I sNumeri c( e. KeyChar ) And Asc( e. KeyChar ) 8 Then

    e. Handl ed = TrueEnd I f

    End Sel ectEnd Sub

    End Cl ass

    Publ i c Enum Ci nputNumer i cOnl yChar actersOnl y

    End Enum

    Ok, let us discuss what we did in the codes above.

    I nheri t s TextboxFirst we Inherits the Textbox class so that we can use all of its properties and methods.

    Publ i c Event OnEnter KeyPress( )Next, we Declared a new event with the name OnEnterKeyPress. We will trigger this eventeach time the user press the Enter key while the cursor is inside the text box.

    Di m MyI nput As Ci nputWe declare an instance of the Cinput. As you have noticed, we've created an enumerationwith 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 aboutEnumeration, you can check out this site http://aspalliance.com/292

    Publ i c Propert y Charact erI nput ( ) As Ci nputGetRet urn Me. MyI nputEnd GetSet ( ByVal val ue As Ci nput)Me. MyI nput = val ueEnd SetEnd Proper t y

    Next, we've created this property to allow the user to specify what type of Character Input hewould 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 butmake sure that you will specify the kind of restriction in the keypress event.

    Protect ed Overr i des Sub OnKeyPr ess( ByVal e AsSyst em. Wi ndows. Forms. KeyPressEvent Ar gs)MyBase. OnKeyPr ess( e)End Sub

    What we did is we overrides the keypress event of the inherited Text box Class so we canadd codes in it. this is where we will put the codes that i have discussed at the beginning ofthis article.

    I f Asc( e. KeyChar ) = 13 ThenRai seEvent OnEnter KeyPress( )End I fThis code simply Raise or Trigger the OnEnterKeyPress event whenever the user press theenter 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 itagain so let's continue to the next step. Build the project by pressing ctrl+shift+b or Rightclick on the project and select Build

    http://aspalliance.com/292http://aspalliance.com/292
  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    5/9

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

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

  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    6/9

    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 theSolution'>'Name of the Project'>Bin>Debug

  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    7/9

    Click Open and then Ok. You'll notice that a new control with the name xTextBox is added inthe 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 newproperty with the name 'CharacterInput' was added to the TextBox control. Show its contentand 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 theplay icon in the tools menu. During runtime, try to enter numbers. The Text box accepted itright? Now, try to type any characters from A-Z, what happened? Amazing... LOL. Now stopthe project and set the Character Input to CharactersOnly and run the project again. Basically

  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    8/9

    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 andin 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 anormal Textbox Control. As you remember, this is the event that we have added a while agoin our xTextBox Class. Click this event and Visual Basic will Automatically generate a subprocedure for this event.

    Now put the codes below inside the OnKeyPress event and run the program again.

    MessageBox. Show( "You Pressed Enter Key" , " " , MessageBoxButt ons. OK,MessageBoxI con. I nformati on)

    Make sure that the cursor is inside the Text box and then press Enter. You will see that eachtime 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 justsome of the powerful features of user controls. Try to experiment by adding codes to yourxTextBox Class. I'll be posting another properties and events for our xTextBox Class soon butI'm afraid I have to end this article for now. Good Luck and Happy Coding!!

  • 7/28/2019 Extending a TextBox Control to Add Custom Properties VB.net 2008

    9/9