我正在尝试将正则表达式添加到下面的代码中,以确保只接受数字。代码非常基础,它计算正方形的面积并将结果放在RichTextBox.Text中 我正在使用VB Visual Studio 2012.任何帮助将不胜感激。
------------------------------------------------------
Public Class SquareArea
Inherits ShapeArea
Public Overrides Function Area() As Double
Return (Me.Lengh ^ 2)
End Function
End Class
------------------------------------------------------------
Public Class Square
Private Sub Square_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub ResultButton_Click(sender As Object, e As EventArgs) Handles ResultButton.Click
Dim area = New SquareArea
area.Lengh = SideTextBox.Text
ResultRichTextBox.Text = area.Area()
End Sub
Private Sub CloseSquareButton_Click(sender As Object, e As EventArgs) Handles CloseSquareButton.Click
Me.Close()
End Sub
End Class
答案 0 :(得分:1)
有几种方法可以做到这一点。但最好的方法是使用SideTextBox文本框的验证事件。
Private Sub SideTextBox_Validating (ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtSideTextBox.Validating
'your code here
End Sub
或 您还可以使用其KeyPress事件,以便在用户输入非数字字符时提示用户。
Private Sub SideTextBox_KeyPress (ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSideTextBox.KeyPress
'your code here
End Sub
答案 1 :(得分:0)
使用此代码...
Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
答案 2 :(得分:0)
我通常不会在Visual Basic中编写,但您希望将RegularExpression作为类成员(System.Text.RegularExpressions命名空间)添加到您的类中。下面显示的正则表达式模式仅允许数字。在正则表达式上调用Match方法会返回一个Match类,您可以将其称为Success on以获得布尔结果(true / false)
您可能需要稍作修改,因为我通常不会用VB编写,但表达式和类是正确的
'Declare Regular Expression Class, Compile once
Dim RegularExpression regex As RegularExpression = New RegularExpression("^[0-9]*$", RegExOptions.Compile)
Private Sub Square_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub ResultButton_Click(sender As Object, e As EventArgs) Handles ResultButton.Click
Dim area = New SquareArea
' Insert Magic Here
If regex.Match(SideTextBox.Text).Success=False Then
MessageBox.Show("Invalid entry")
Return
End If
area.Lengh = SideTextBox.Text
ResultRichTe...
Private Sub CloseSquareButton_Click(sender As Object, e As EventArgs) Handles CloseSquareButton.Click
Me.Close()
End Sub
End Class