Call a keypress method dynamically for each control in vb.net 2005
I working on a project that includes to call a certain type of method to each control, i have this code:
Private Sub txtBcNum1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPress开发者_JS百科EventArgs) Handles txtBcNum1.KeyPress
If Char.IsDigit(e.KeyChar) Or e.KeyChar = Chr(8) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
This code works like a charm if i want to allow only numbers and backspace on my textbox.
Problem: I have 15 textboxes( txtBcNum1,txtBcNum2,....,txtBcNum15 ), what's the best way to call this function inside KeyPress method on each textboxes with out manually adding it to KeyPress method?
You can add more than one control to the Handles clause:
Private Sub txtBcNum1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles txtBcNum1.KeyPress, txtBcNum2.KeyPress, txtBcNum3.Keypress, ...
This way your sub will be called for every control. If you want to reuse this code across different forms, it might be a good idea to create a new control, inherited from Textbox, which might be called NumericTextBox and handle its own KeyPress event. That way you wouldn't have to add any code in forms that use this control.
Also, have you considered using the built-in NumericUpDown control which serves the same purpose?
精彩评论