我编写了一个用于验证文本字段中数字输入的函数,即“txtDiaThick”。如何使这个函数通用,以便它可以处理所有数字字段?例如,我如何使“txtDiaThick.Focus()”通用?
这是代码。
Private Sub txtDiaThick_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtDiaThick.Validating
If Not IsNumeric(txtDiaThick.Text) And txtDiaThick.Text <> String.Empty Then
MessageBox.Show("Diameter must be numeric")
e.Cancel = True
txtDiaThick.Focus()
Exit Sub
End If
End Sub
答案 0 :(得分:2)
您将使用sender
参数,该参数表示引发事件的控件:
Private Sub NumericTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtDiaThick.Validating, …
Dim numericTextBox As TextBox = DirectCast(sender, TextBox)
If numericTextBox.Text <> String.Empty AndAlso Not IsNumeric(numericTextBox.Text) Then
MessageBox.Show("Diameter must be numeric")
e.Cancel = True
numericTextBox.Focus()
End If
End Sub
尽管如此,请考虑使用专用于数字的控件。