0

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

#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 
4

2 回答 2

6

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

TextBox1.MaxLength = 1

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

于 2013-09-29T16:37:16.017 回答
1

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

 <asp:TextBox ID="txt_enter" runat="server" MaxLength="1"></TextBox>
于 2013-10-01T07:58:07.560 回答