在TextBox中只允许使用1个字符

时间:2013-09-29 16:28:20

标签: .net vb.net winforms textbox code-snippets

我编写了一个通用代码段,只允许TextBox中的一个字符有多种方式,代码工作得很好,但问题是代码大小已经非常广泛,所以我想知道如果代码可以提出建议或修改简化:

#Region " [TextBox] Allow only 1 Character "


' By Elektro H@cker


' TextBox [Enter]
Private Sub TextBox_Enter(sender As Object, e As EventArgs) ' Handles TextBox1.MouseEnter

    ' Allign the character in the TextBox space
    ' If Not TextBox_Separator.TextAlign = HorizontalAlignment.Center Then TextBox_Separator.TextAlign = HorizontalAlignment.Center Then

    ' Disable Copy/Paste contextmenu by creating a new one
    If sender.ContextMenuStrip Is Nothing Then sender.ContextMenuStrip = New ContextMenuStrip

End Sub

' TextBox [KeyPress]
Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) ' Handles TextBox1.KeyPress

    Select Case sender.TextLength

        Case 0 ' TextLength = 0

            Select Case e.KeyChar

                Case Chr(22) ' CTRL+V is pressed

                    ' If Clipboard contains 0 or 1 character then paste the character.
                    e.Handled = IIf(Clipboard.GetText.Length <= 1, False, True)

                Case Else ' Other key is pressed
                    e.Handled = False ' Print the character.

            End Select ' e.KeyChar when TextLength = 0

        Case 1 ' TextLength = 1

            Select Case e.KeyChar

                Case Convert.ToChar(Keys.Back) ' Backspace is pressed
                    e.Handled = False ' Delete the character

                Case Chr(22) ' CTRL+V is pressed

                    Select Case sender.SelectionLength

                        Case 1 ' If 1 character is selected
                            ' If Clipboard contains 0 or 1 character then paste the character.
                            e.Handled = IIf(Clipboard.GetText.Length <= 1, False, True)

                        Case Else ' If any text is selected
                            e.Handled = True ' Don't paste the characters.

                    End Select

                Case Else ' Other key is pressed
                    ' If any text is selected then don't print the character.
                    e.Handled = IIf(sender.SelectionLength = 1, False, True)

            End Select ' e.KeyChar when TextLength = 1

    End Select ' TextLength

End Sub

#End Region 

2 个答案:

答案 0 :(得分:5)

这很简单。你的代码过于复杂。

TextBox1.MaxLength = 1

您甚至可以在属性窗口中执行此操作。

答案 1 :(得分:1)

修正文本框的长度......

 <asp:TextBox ID="txt_enter" runat="server" MaxLength="1"></TextBox>