19 สิงหาคม 2554

การใช้งาน AddHandler (ตัวอย่าง TextBox ให้รับค่าตัวเลขอย่างเดียว)

    Sub AddCurrencyTextBox()
        Try
            'เมื่อเกิดการพิมพ์ค่าเข้า Textbox ให้เรียก Function  keypressed
            AddHandler TextBox1.KeyPress, AddressOf keypressed
            AddHandler TextBox2.KeyPress, AddressOf keypressed
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub keypressed(ByVal o As [Object], ByVal e As KeyPressEventArgs)
        e.Handled = NumbericOnly(o, e.KeyChar)
    End Sub 'keypressed

    Public Function NumbericOnly(ByVal TargetTextBox As Windows.Forms.TextBox, ByVal CurrentChar As Char, Optional ByVal bIsUseSign As Boolean = True) As Boolean
        Try
            If IsNumeric(CurrentChar) = True Then
                Return False
            End If

            If CurrentChar = vbBack Then
                Return False
            End If

            If Convert.ToString(CurrentChar) = "+" OrElse Convert.ToString(CurrentChar) = "-" Then
                If bIsUseSign Then
                    Return False
                Else
                    Return True
                End If
            End If

            Return True
        Catch ex As Exception
            Throw ex
        End Try

    End Function

0 ความคิดเห็น:

แสดงความคิดเห็น