location of "." in a numeric string

  • Thread starter Thread starter Bernie Yaeger
  • Start date Start date
B

Bernie Yaeger

I'm trying to control the textbox keypress event to deal with a "." such
that it disallows a second "." and no characters after 2 numbers beyond the
"." (thus a currency value). I have no problem with the numeric characters,
but I am using this to identify how many chars are after the ".", but it's
not working:

Dim pos As Integer

pos = InStr(1, ratevar1.Text, ".")

If pos <> 0 And ratevar1.Text.Length - pos = 2 Then

SendKeys.Send("{BACKSPACE}")

Exit Sub

End If

This hangs up and continually calls the keypress event. How can I simply
identify that the decimal point has 2 chars behind it and exit the sub
gracefully?

Thanks for any help.

Bernie Yaeger
 
Change to > 2 rather than = 2 then it will work

If pos <> 0 And TextBox1.Text.Length - pos > 2 Then
 
Hi Bernie,

Very Quick and dirty

if strField.indexof(".") <> -1 then
if strField.lastindexof(".") = strField.indexof(.) then
correct
else
error
end if
end if

Try it, I think it works.

Cor
 
Put this into your keypress event. This is better than printing a char and
then sending a backspace to the textbox to remove it.

Dim pos As Integer

pos = InStr(1, TextBox1.Text, ".")

If pos > 0 And e.KeyChar = "." Then
e.Handled = True
ElseIf pos > 0 And TextBox1.Text.Length - pos = 2 Then
If e.KeyChar <> ControlChars.Back Then e.Handled = True
End If
 
Hi Bernie,

Looking it over and then of course in the key event as Brian also said.

That first test is even not necessary because
-1 = -1 is also correct
if strField.lastindexof(".") = strField.indexof(.) then
correct
else
error
end if

Cor
 
Hi Brian,

Tx for your response. I actually have been working on this in the interim
and came up with the same realization re backspace and e.handled.

Tx again,

Bernie
 
Hi Cor,

Tx for your response. I came up with a way to handle this by placing this
in the textchanged event:
Dim pos, x As Integer

pos = InStr(1, ratevar1.Text, ".")

x = ratevar1.Text.Length - pos

If pos <> 0 And x > 2 Then

ratevar1.Text = Math.Round(CDec(ratevar1.Text) - 0.005, 2)

Exit Sub

End If

Tx again,

Bernie
 
* "Bernie Yaeger said:
I'm trying to control the textbox keypress event to deal with a "." such
that it disallows a second "." and no characters after 2 numbers beyond the
"." (thus a currency value). I have no problem with the numeric characters,
but I am using this to identify how many chars are after the ".", but it's
not working:

Very "user friendly": In German, we use "," as a decimal point.
Globalization is important...
 
Hi Herfried,

I knew there was an error in the indexof(.}

I said it was very quick and dirty, I saw it in the first and forgot to
correct it even in the second, but what is the other error?

Cor
 
Back
Top