給一個文本框,只能輸入數字、小數點和負號,其他的按鍵輸入將不顯示。
1.普通程序代碼控制
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim c As Char
c = e.KeyChar
If c = "."c Then
If InStr(TextBox1.Text, e.KeyChar) > 0 Or (InStr(TextBox1.Text, "-") > 0) And (TextBox1.SelectionStart = 0) Then
e.KeyChar = ""
End If
ElseIf c = "-"c Then
If InStr(TextBox1.Text, c) > 0 Or TextBox1.SelectionStart > 0 Then
e.KeyChar = ""
End If
ElseIf c = "0"c Then
If (TextBox1.SelectionStart = 0 And Not TextBox1.Text.StartsWith("0") And TextBox1.Text.Length <> 0) Or (TextBox1.SelectionStart <= 1 And TextBox1.Text.StartsWith("0")) Then
e.KeyChar = ""
End If
ElseIf c = ControlChars.Back Then
ElseIf InStr("123456789", e.KeyChar) <= 0 Then
e.KeyChar = ""
End If
End Sub
2.正則表達式控制//正則表達式不對
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
'利用正則表達式驗證
'System.Text.RegularExpressions.Regex.IsMatch(TextBox2.Text, "^(-?\\d+)(\\.\\d+)?$") ''''該表達式來源與網上,未經證實
End Sub
// ^[+-]?(?:\d+\.?\d*|\d*\.?\d+)[\r\n]*$ 據說這個是對的。未驗證。
3.使用MaskedTextBox//不能輸入-和。
Mask屬性設置的是自定義掩碼爲999999999999999
===============================================
將窗體中所有TextBox的text全部清空,其他的CheckBox啊RadioButton啊這些照舊
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tp As TabPage
Dim text As Control
For Each tp In TabControl1.TabPages
For Each text In tp.Controls
If TypeOf text Is TextBox Then
text.Text = ""
End If
Next
Next
End Sub