简体   繁体   中英

if textbox has string then show msgbox but the (.) doesnt count. visual basic

i have this textbox where i want to input only number the (.) included. for example is 190.5.

but if it has text for example 190.5g then it will show msgbox("error")

i have this code i found somewhere

 Dim allDigit = pbox.Text.Trim.Length <> 0 AndAlso _
      pbox.Text.All(Function(chr) Char.IsDigit(chr))
        If Not allDigit Then
            MsgBox("Please input number only on price")
            pbox.Clear()
            Exit Sub
        End If

if i add . on the number it shows the msgbox so is there anyway to include the . ?

Check out Decimal.TryParse , rather than pulling the string apart yourself.

Dim value As Decimal
Dim yourString As String = "1234"
If Not Decimal.TryParse(yourString, value) Then
    MsgBox("Please input number only on price")
    pbox.Clear()
    Exit Sub
End If

It should be noted that the character that represents the decimal separator will vary depending on the language settings of the OS - for American / British English it'll be period, for German it'll be comma.

Use IsNumeric function instead

    If Not IsNumeric(pbox.Text) Then
        MsgBox("Please input number only on price")
        pbox.Clear()
        Exit Sub
    End If

This is my code in c# which i use

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) 
            && !char.IsDigit(e.KeyChar) 
            && e.KeyChar != '.')
        {
                            //message box
            e.Handled = true;
        }

        // only allow one decimal point
        if (e.KeyChar == '.' 
            && (sender as TextBox).Text.IndexOf('.') > -1)
        {
                            //message box
            e.Handled = true;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM