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

1

テキストボックスの長さを修正....

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