任何人都可以简化我的vb.net代码

时间:2015-08-07 03:51:44

标签: vb.net

任何人都可以帮我简化这段代码,因为我需要在更多行中扩展相同的方式,这会让我的代码看起来很笨重

    Private Sub tb11_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb11.KeyPress
    If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
        tb11.Text = e.KeyChar
    End If
End Sub
Private Sub tb12_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb12.KeyPress
    If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
        tb12.Text = e.KeyChar
    End If
End Sub
Private Sub tb13_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb13.KeyPress
    If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
        tb13.Text = e.KeyChar
    End If
End Sub
Private Sub tb14_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb14.KeyPress
    If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
        tb14.Text = e.KeyChar
    End If
End Sub

2 个答案:

答案 0 :(得分:4)

创建一个运行检查的单个事件处理程序,然后更改发件人文本。请记住首先将发件人转换为TextBox

Private Sub TextBox_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) 
Handles tb11.KeyPress, tb12.KeyPress, tb13.KeyPress, tb14.KeyPress

    If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
        DirectCast(sender, TextBox).Text = e.KeyChar
    End If
End Sub

答案 1 :(得分:-3)

在所有事件侦听器函数之上,您正在检查相同的条件 您可以将该条件移动到其他方法并将对象传递给它