Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a array of textboxes in a form. the array has 10 textboxes in it and i want to validate each textbox on key press it will be very lengthy if i do that so i want to use the krypress through array of textbox i have tries this code can u tell me hoe i should use it with array of textboxes

VB
Dim TxtFrom() As TextBox = {txtfr1, txtfr2, txtfr3, txtfr4, txtfr5, txtfr6, txtfr7, txtfr8, txtfr9}

        Dim TxtTo() As TextBox = {txtTo1, txtTo2, txtTo3, txtTo4, txtTo5, txtTo6, txtTo7, txtTo8, txtTo9}
  Private Sub txtfr1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtfr1.KeyPress
        e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".")
    End Sub
Posted

1 solution

Make a loop in the array of text boxes; in this loop, add an event handler to every one; in the event handler, use the same method to deal with the sender, which will be a reference to a particular text box.

If this is just validation, is some cases you won't even need to know a reference to each of the text boxes is passed to the event handling method. However, usually this is needed. The only information you can use is the reference to the sender, passed as a first parameter of the event handler.

First, you can always type-case this reference to TextBox, because, in this scenario, this is always the sender. So, you get a reference to an instance of the TextBox. To pass additional information, you can use the property TextBox.Tag (inherited from Control.Tag). In your case, it would be the best to assign an index in your array to this Tag. In the event handler, you type-cast Tag to int and this way know the index of the array element being handled.

[EDIT]

I almost forgot, VB.NET does not have '+=' operator for adding a handler to an invocation list of an event instance. You need to use AddHandler. This is shown in a code sample here, see the answer #0:
http://stackoverflow.com/questions/4199370/how-to-create-event-for-dynamic-control-array-in-vb-net[^].

—SA
 
Share this answer
 
v2
Comments
Pratik65 26-Dec-12 1:44am    
its too compliacted i didnt understood the example can u explain me in a simple way please how to use keypress in textbox array
Sergey Alexandrovich Kryukov 26-Dec-12 2:01am    
If you don't understand it at all, perhaps you are not ready for UI development yet. It hardly can be simpler than that (and I don't have VB.NET compiler to develop a sample and not going to install it, sorry), and all this is really very simple. Did you understand the code sample I referenced?
However, if you tell me which part you don't understand, I'll gladly clarify it.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900