蓝色经典

导航

TEXTBOX只输入小数点和数字,限制位数并固定格式

 Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
      
        If (Char.IsNumber(e.KeyChar) Or e.KeyChar = "." Or Convert.ToInt32(e.KeyChar) = 8) And CType(sender, TextBox).Text.Length < 6 Then
            Dim point_amount As Int16 = 0                 '小数点的个数
            Dim point_flag As Boolean = False             '小数点标记
            Dim point_position As Int16 = 0               '小数点的位置
            If e.KeyChar = "." And InStr(CType(sender, TextBox).Text, ".") > 0 Then
                e.Handled = True
            Else
                e.Handled = False
            End If

            If InStr(CType(sender, TextBox).Text, ".") > 0 Then
                point_flag = True
                point_position = InStr(CType(sender, TextBox).Text, ".")
            End If

         ‘ 只能输入两位小数

            If point_flag = True And point_position < CType(sender, TextBox).Text.Length - 2 Then

                If Char.IsNumber(e.KeyChar) Or e.KeyChar = ChrW(Keys.Back) Then

                    e.Handled = False
                Else
                    e.Handled = True
                End If
            ElseIf point_flag = False And point_position < CType(sender, TextBox).Text.Length - 2 Then
                If Char.IsNumber(e.KeyChar) Or e.KeyChar = ". " Or Convert.ToInt32(e.KeyChar) = 8 Then
                    e.Handled = False
                End If
            ElseIf point_flag = True And Strings.Mid(CType(sender, TextBox).Text, point_position + 1).Length > 1 Then
                If Convert.ToInt32(e.KeyChar) = 8 Then
                    e.Handled = False
                Else
                    e.Handled = True
                End If

            End If
        Else

            If Convert.ToInt32(e.KeyChar) = 8 Then
                e.Handled = False
            Else
                e.Handled = True
                Exit Sub
            End If
        End If
    End Sub

 
    Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
        If e.KeyCode = Keys.Enter Then

            If InStr(TextBox1.Text, ".") = TextBox1.Text.Length Then
                TextBox1.Text = CInt(TextBox1.Text).ToString("##0.00")
            ElseIf InStr(TextBox1.Text, ".") = TextBox1.Text.Length - 1 Then
                TextBox1.Text = CDbl(TextBox1.Text).ToString("##0.#0")
            ElseIf InStr(TextBox1.Text, ".") = TextBox1.Text.Length - 2 Then
                TextBox1.Text = CDbl(TextBox1.Text).ToString("##0.##")
            End If
            TextBox1.SelectionStart = TextBox1.Text.Length
        End If
    End Sub

posted on 2011-09-07 12:39  蓝色经典  阅读(1059)  评论(1编辑  收藏  举报