我正在制作表单,其中名称字段只能包含字母,空格和退格。如果用户试图输入任何其他东西,它将由异常处理程序处理,但我将以标签的形式显示消息" *只允许使用字母,空格和退格键。"。但是,当用户尝试重新输入正确的密钥时,程序必须在文本字段附近移动警告消息,但我使用标签并尝试删除其文本或处理并删除整个对象仍然保留,因为它靠近该文本字段..请帮我修理一下。
代码在这里
Public Class Form1
Dim Flag As Boolean = False
Private Sub TxtName_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtName.KeyPress
Dim Txt As Integer = Asc(e.KeyChar)
Dim Lbl As New Label
If (Txt < 65 Or Txt > 90) And (Txt < 97 Or Txt > 122) And Txt <> 8 And Txt <> 32 Then
e.Handled = True
Lbl.Text = "*Only Alphabets, Space and" & vbNewLine & "Backspace are allowed."
Lbl.AutoSize = True
Lbl.Name = "LblError"
Lbl.ForeColor = Color.Red
Lbl.Location = TxtName.Location + New Point(175, 0)
GrpBxDataInput.Controls.Add(Lbl)
Flag = True
ElseIf Flag = True Then
Lbl.Text = " "
Lbl.Location = TxtName.Location + New Point(175, 0)
'GrpBxDataInput.Controls.Remove(Lbl)
'Lbl.Dispose()
Flag = False!
End If
End Sub
End Class
答案 0 :(得分:0)
如果我是对的,那么问题是,每次调用keypress-function时都会创建一个新标签。你最终得到了一堆标签 我建议你按照我在你的问题评论中提到的那样做:在设计师中创建一个标签并将其切换(可见):
Public Class Form1
...
// part of the designer block:
GrpBxDataInput.Controls.Add(MyWarningLabel)
Private Sub TxtName_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtName.KeyPress
Dim Txt As Integer = Asc(e.KeyChar)
If (Txt < 65 Or Txt > 90) And (Txt < 97 Or Txt > 122) And Txt <> 8 And Txt <> 32 Then
e.Handled = True
MyWarningLabel.Text = "*Only Alphabets, Space and" & vbNewLine & "Backspace are allowed."
MyWarningLabel.Visible = True
Else
MyWarningLabel.Text = ""
MyWarningLabel.Visible = false
End If
End Sub
End Class
答案 1 :(得分:0)
在vb [design]中添加新标签后,可以从代码中手动查看。这是解决方案:
Dim Flag As Boolean = False
Private Sub TxtName_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtName.KeyPress
Dim Txt As Integer = Asc(e.KeyChar)
If (Txt < 65 Or Txt > 90) And (Txt < 97 Or Txt > 122) And Txt <> 8 And Txt <> 32 Then
e.Handled = True
Lbl.Text = "*Only Alphabets, Space and" & vbNewLine & "Backspace are allowed."
Lbl.AutoSize = True
Lbl.ForeColor = Color.Red
Lbl.Visible = True
Flag = True
ElseIf Flag = True Then
Lbl.Visible = False
Flag = False
End If
End Sub