Need change char in input

Hi guys, I need to change the comma to point, when I insert values ​​in a textfield, I tried in the KeyUp event to write:

if key=chr(44) then 'Cambia da virgola a punto
  key=chr(46)
  messagebox " OK  ??"
end if

the event recognizes it but the value is not reassigned, why?

You may use a variable:

Dim MyKey as string
if key=chr(44) then ' Cambia da virgola a punto
  MyKey=chr(46)
  messagebox " OK  ??"
else
  MyKey = key
end if ' Continue the code using MyKey

Instead of doing that in KeyUp, do this in Keydown:

Function KeyDown(key As String) Handles KeyDown as Boolean
  if key=chr(44) then 'Cambia da virgola a punto
    'key=chr(46)
    If me.SelectionStart < me.text.Length then
      me.text = me.text.Left(me.Selectionstart) + chr(46) + me.text.Right(me.text.Length-me.SelectionStart)
    else
      me.text = me.text + chr(46) //dot
    end if
    me.selectionstart = me.selectionstart + 1
    return true
  end if
End Function

This will insert the dot instead of the coma. The code takes into account cases when the insertion is at the right of text, or in the middle.

it doesn’t work for me, I understand what you are trying to do … but when I press the comma, it puts the period but it doesn’t move to the right position, it moves to the second digit after the start.

Hi Michel Bujardet
i have just solved:

if key=chr(46) then 'if dot
  If me.SelectionStart < me.text.Length then
    me.text = me.text.Left(me.Selectionstart) + chr(44) + me.text.Right(me.text.Length+me.SelectionStart)
  else
    me.text = me.text + chr(44) //comma
  end if
  me.selectionstart = me.selectionstart + me.text.Length
  return true
end if

changing just one small thing now it works great.

I tested the code before posting. It behaves as expected. The caret moves one position after the inserted dot, as it would with any other character.

Perhaps that works when there is nothing in the textfield, but when the caret is in the middle of text (If me.SelectionStart < me.text.Length), that won’t work.

No, you almost certainly don’t.

In Europe, the decimal character is a comma
In the UK and USA, it is a period

If your software runs indifferent countries, you need to accept that people will describe 1/2 as
0,5 in France and 0.5 In England/USA

You store it as a double, and display it in the form that people expect to see it.

To take a value from a text box and get a double from it, use CDBL()
That understands the user language preference and turns 0,5 or 0.5 into 1/2

When you display what you have recorded, format the number using Format(), and it will insert comma or period accordingly.

2 Likes

In the key down event:

If key=chr(44) Then //you can use ","
  Var s As Integer=Me.SelectionStart
  Me.SelectedText=chr(46) //you can use "."
  Me.SelectionStart=s+1
  Return True
End If

Thanks, work fine.